处理中………………
”:如何解决数据库事务问题?
Python3 程序执行数据库操作时报错 “
处理中………………
”:如何解决数据库事务问题?
小伙伴们有没有觉得学习很有意思?有意思就对了!今天就给大家带来
处理中………………
”:如何解决数据库事务问题? 》,以下内容将会涉及到 ,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
处理中………………
”:如何解决数据库事务问题? ” />
python3 程序报错
在执行一段业务代码时,出现 “<p>处理中………………</p>” 的错误提示。
经过排查,发现代码中的数据库操作部分有问题,具体代码如下:
import requests import time import json import pymysql mydb = pymysql.connect( host="92.68.40.12", port=3306, user="root", password="iss_root", database="dynamic_premium_db" ) mycursor = mydb.cursor() def excute_sql_db(stratagy_id, city_id, app_name, total_price, over_flow_price, date_time): sql = "insert into over_flow_price(straragy_id,city_id,app_name,total_price,over_flow_price,time_stamp)values('%s','%s','%s','%s','%s','%s')" % (stratagy_id, city_id, app_name, total_price, over_flow_price, date_time) mycursor.execute(sql) # 报错行
解决方案:
通过仔细分析代码,发现代码中缺少对数据库事务的处理。在数据库操作中,特别是涉及到多个表的操作时,需要使用事务来保证数据的完整性。
修改后的代码如下:
def excute_sql_db(stratagy_id, city_id, app_name, total_price, over_flow_price, date_time): sql = "INSERT INTO over_flow_price(straragy_id,city_id,app_name,total_price,over_flow_price,time_stamp)VALUES('%s','%s','%s','%s','%s','%s')" % (stratagy_id, city_id, app_name, total_price, over_flow_price, date_time) try: mycursor.execute(sql) mydb.commit() # 提交事务 print('插入成功') except Exception as e: mydb.rollback() # 回滚事务 print('err: ' + sql) print(e)
到这里,我们也就讲完了《Python3 程序执行数据库操作时报错 “
处理中………………
”:如何解决数据库事务问题? 》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注主机宝贝公众号,带你了解更多关于的知识点!