问题
I have a string that is basically a concatenation of multiple insert statements such as
sql = INSERT INTO test (a,b,c) VALUES ("test","test",1);INSERT INTO test (a,b,c) VALUES ("2nd test","2nd test",6);
When I run this in SQL as a query, it works fine and inserts both statements.
However, when I run it in python using the following:
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()
I get this error:
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
Whats the best way to resolve this and execute multiple statements in one go?
Thanks!
回答1:
This error is about the fact that cursor.execute
can handle only one sql per run. you either want to loop it:
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)
or execute at once:
sql = 'INSERT INTO test (a,b,c) VALUES ("test","test",1),("2nd test","2nd test",6)'
cursor.execute(sql)
来源:https://stackoverflow.com/questions/20104519/executing-multiple-mysql-inserts-at-once-in-python