我有一个字符串,它基本上是多个插入语句的串联,例如
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")
解决这个问题并一次执行多个语句的最佳方法是什么?
谢谢!
答案 0 :(得分:2)
这个错误是关于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)