Abdul Razak
Abdul Razak

Reputation: 2804

Insert multiple rows to database without using looping

I have following psql query to insert data to database

sql = ("INSERT INTO kart_user (custid,token,cycle,userid,proxyid,salesrepid,users,buyer,salesrep,validfrom,validto,discount,category,ratioOnly,proxy,notified) ""VALUES (%s, %s, %s, %s,%s, %s, %s, %s,%s, %s, %s, %s,%s, %s, %s, %s)")
result = self.cur.execute(sql,data)
self.dbconn.commit()
return result

Now, the problem I facing ,in some case data may contain multiple rows.in this case how can i rewrite my code. Note: I don't like to use for loop for data iteration ,please suggest better way to solve this issue.

Upvotes: 4

Views: 1298

Answers (1)

alecxe
alecxe

Reputation: 474141

executemany() would help:

result = self.cur.executemany(sql, data)

data in this case should be a list of lists or a list of tuples.

Upvotes: 4

Related Questions