Python3 程序执行数据库操作时报错 “<p>处理中………………</p>”:如何解决数据库事务问题?

Python3 程序执行数据库操作时报错 “<p>处理中………………</p>”:如何解决数据库事务问题?处理中………………

”:如何解决数据库事务问题? ” />

python3 程序报错

在执行一段业务代码时,出现 “

处理中………………

” 的错误提示。

经过排查,发现代码中的数据库操作部分有问题,具体代码如下:

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)  # 报错行

解决方案:

立即学习Python免费学习笔记(深入)”;

通过仔细分析代码,发现代码中缺少对数据库事务的处理。在数据库操作中,特别是涉及到多个表的操作时,需要使用事务来保证数据的完整性。

修改后的代码如下:

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)

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享