Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中一次执行多个MySQL插入_Python_Mysql_Mysql Python - Fatal编程技术网

在Python中一次执行多个MySQL插入

在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

我有一个字符串,它基本上是多个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 (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)

完美的非常感谢。由于各种原因,他们需要一次全部进入,所以第二种方法有效。