如何在Python中同时处理和执行多个SQL?
我试图在如何在Python中同时处理和执行多个SQL?,python,mysql,sql,mysql-python,Python,Mysql,Sql,Mysql Python,我试图在for循环中执行多个查询。因此,在每个循环中,如果其中一个查询执行失败,则该循环中的所有查询将不会提交到数据库,并返回失败的查询的错误消息。下面是我的代码。似乎即使有一个查询未能运行,其他查询仍将执行并将数据提交到数据库。我如何改变它来实现我想要的?谢谢 代码: 您需要将mydb连接设置为非自动提交 mydb.autocommit = False 您需要将mydb连接设置为非自动提交 mydb.autocommit = False 这就是我编写代码的方式 import mysql.c
for循环中执行多个查询
。因此,在每个循环
中,如果其中一个查询
执行失败,则该循环
中的所有查询
将不会提交到数据库
,并返回失败的查询
的错误消息。下面是我的代码。似乎即使有一个查询
未能运行,其他查询仍将执行并将数据提交到数据库
。我如何改变它来实现我想要的?谢谢
代码:
您需要将
mydb
连接设置为非自动提交
mydb.autocommit = False
您需要将
mydb
连接设置为非自动提交
mydb.autocommit = False
这就是我编写代码的方式
import mysql.connector
mydb = mysql.connector.connect()
cursor = mydb.cursor()
query1 = "call_sp_insert_sth_1" //insert data to DB
query2 = "call_sp_insert_sth_2" //insert data to DB
query3 = "call_sp_insert_sth_3" //update data to DB
for i in country_list:
try:
with mydb.cursor() as curs:
cursor.execute(query1)
cursor.execute(query2)
cursor.execute(query3)
curs.close()
except Exception as err:
fail_list.append('error':err.msg)
else:
mydb.commit()
我倾向于将查询作为带有参数的for循环之外的变量,然后在循环中填充参数
myquery = '''select * from {}'''
for table in tables:
curs.execute(myquery.format(table))
只有在“try”部分没有错误时,“else”部分才会启动。这就是我编写代码的方式
import mysql.connector
mydb = mysql.connector.connect()
cursor = mydb.cursor()
query1 = "call_sp_insert_sth_1" //insert data to DB
query2 = "call_sp_insert_sth_2" //insert data to DB
query3 = "call_sp_insert_sth_3" //update data to DB
for i in country_list:
try:
with mydb.cursor() as curs:
cursor.execute(query1)
cursor.execute(query2)
cursor.execute(query3)
curs.close()
except Exception as err:
fail_list.append('error':err.msg)
else:
mydb.commit()
我倾向于将查询作为带有参数的for循环之外的变量,然后在循环中填充参数
myquery = '''select * from {}'''
for table in tables:
curs.execute(myquery.format(table))
“else”部分只有在“try”部分没有错误时才会启动。你的问题有点不清楚——你是说如果query3失败,你希望query1和query2回滚吗?@JohnGordonyes@WILLIAM . . . 存储过程本身可能会将更改提交到数据库,因此这可能很棘手。将三个查询合并到一个存储过程可能更有意义。您的问题有点不清楚——您是说如果query3失败,您希望回滚query1和query2吗?@JohnGordonyes@WILLIAM . . . 存储过程本身可能会将更改提交到数据库,因此这可能很棘手。将三个查询合并到一个存储过程可能更有意义。