如何使用python mysqldb一次插入许多行 [英] How to use python mysqldb to insert many rows at once

查看:86
本文介绍了如何使用python mysqldb一次插入许多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,例如[['a','b'],['c','d']].

I have a list of lists, e.g [['a','b'],['c','d']].

我有一个名为T的表和两个字段F1F2.字段列表中的第一项映射到F1,第二项映射到F2.

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

如何在单个命令或调用中为每个内部列表插入行,而不是像这样使用for循环?

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]))

推荐答案

来自 MySQLdb用户指南:

c.executemany(
      """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 )
      ] )

所以在您的情况下:

c.executemany("insert into T (F1,F2) values (%s, %s)",
    [('a','b'),('c','d')])

这篇关于如何使用python mysqldb一次插入许多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆