在Python中一次执行多个MySQL插入
我有一个字符串,它基本上是多个insert语句的串联,例如在Python中一次执行多个MySQL插入,python,mysql,mysql-python,Python,Mysql,Mysql Python,我有一个字符串,它基本上是多个insert语句的串联,例如 sql = INSERT INTO test (a,b,c) VALUES ("test","test",1);INSERT INTO test (a,b,c) VALUES ("2nd test","2nd test",6); 当我在SQL中以查询的形式运行它时,它可以很好地工作并插入这两条语句 但是,当我在python中使用以下命令运行它时: cursor = db.cursor() sql = INSERT INTO test
sql = INSERT INTO test (a,b,c) VALUES ("test","test",1);INSERT INTO test (a,b,c) VALUES ("2nd test","2nd test",6);
当我在SQL中以查询的形式运行它时,它可以很好地工作并插入这两条语句
但是,当我在python中使用以下命令运行它时:
cursor = db.cursor()
sql = INSERT INTO test (a,b,c) VALUES ("test","test",1);INSERT INTO test (a,b,c) VALUES ("2nd test","2nd test",6);
cursor.execute(sql)
db.commit()
我得到这个错误:
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
解决这个问题并一次性执行多个语句的最佳方法是什么
谢谢 此错误与以下事实有关:
cursor.execute
每次运行只能处理一个sql。要循环它,请执行以下操作:
sql = 'INSERT INTO test (a,b,c) VALUES (%s, %s, %s)'
for values in [("test","test",1), ("2nd test","2nd test",6)]
cursor.execute(sql, values)
或立即执行:
sql = 'INSERT INTO test (a,b,c) VALUES ("test","test",1),("2nd test","2nd test",6)'
cursor.execute(sql)
完美的非常感谢。由于各种原因,他们需要一次全部进入,所以第二种方法有效。