Tampa Tampa - 1 year ago 94
MySQL Question

How to use python mysqldb to insert many rows at once

I have a list of lists, e.g


I have a table called
and two fields
. The first item in the field list maps to
, second to

How can I insert rows for each inner list in a single command or call, rather than using a for loop like this?

for i in [['a','b'],['c','d']]:
c.execute("insert into T (F1,F2) values (%s, %s)", (i[0], i[1]))

Answer Source

From MySQLdb User's Guide:

      """INSERT INTO breakfast (name, spam, eggs, sausage, price)
      VALUES (%s, %s, %s, %s, %s)""",
      ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
      ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
      ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
      ] )

so in your case:

c.executemany("insert into T (F1,F2) values (%s, %s)",