简体   繁体   中英

python mysql multi-row insert fail

i'm just trying to insert data into a small mysql (innodb) table i made for testing. the single row insert works:

cursor.execute("insert into testy (one, two) values (%s,%s)", ('00','01'))

but multiple row insert fails:

cursor.execute("insert into testy (one, two) values (%s,%s)", [('00','01'),('10','11'),('20','21')])

and gives the following error:

TypeError - not all arguments converted during string formatting

traceback:
  File "./testy.py", line 20, in <module>
    cursor.execute("insert into testy (one, two) values (%s,%s)", [('00','01'),('10','11'),('20','21')])
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute
    query = query % db.literal(args)

i need to do the multi-row insert as it is much quicker than looping over the single row inserts. what am i doing wrong?

Use executemany method instead of execute :

cursor.executemany("insert into testy (one, two) values (%s,%s)",
                   [('00','01'),('10','11'),('20','21')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM