如何使用python mysqldb一次插入多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14011160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:10:02  来源:igfitidea点击:

How to use python mysqldb to insert many rows at once

pythonmysqlmysql-python

提问by Tampa

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

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

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

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

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

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

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

采纳答案by zenpoy

From MySQLdb User's Guide:

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

so in your case:

所以在你的情况下:

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

回答by Rems

It's possible to insert all rows in one single statement like @adamhajari, and avoid sql injections like @zenpoy, at the same time. You just need to create a big insert statement and let mysqldb's executedo the formatting.

可以像@adamhajari 这样在一条语句中插入所有行,同时避免像@zenpoy 这样的sql 注入。您只需要创建一个大的插入语句并让 mysqldbexecute进行格式化。

values_to_insert = [('a','b'),('c','d')]
query = "INSERT INTO T (F1, F2) VALUES " + ",".join("(%s, %s)" for _ in values_to_insert)
flattened_values = [item for sublist in values_to_insert for item in sublist]
c.execute(query, flattened_values)

Not super readable, but can be slightly faster than executemany (I tried inserting batches of 50000 rows in a local DB, executemany was 20% slower).

不是超级可读,但可以比 executemany 稍快(我尝试在本地数据库中插入 50000 行的批次,executemany 慢了 20%)。

回答by PHPJungle

def multiple_insert(cursor, table, cols, rows):
    sql_insert = 'INSERT INTO %s(%s) values %s' % (
        table,
        ','.join(cols),
        ','.join('(%s , %s)' for _ in rows)
    )
    values = [_ for r in rows for _ in r]
    cursor.execute(sql_insert, values)


# eg:
rows = [(a1 , b1),(a2 , b2),(a3 , b3)]
multiple_insert(cursor, 'your_table',('col1', 'col2'), rows)
conn.commit()