處理中………………
”:如何解決數(shù)據(jù)庫事務(wù)問題? ” />
python3 程序報錯
在執(zhí)行一段業(yè)務(wù)代碼時,出現(xiàn) “
處理中………………
” 的錯誤提示。
經(jīng)過排查,發(fā)現(xiàn)代碼中的數(shù)據(jù)庫操作部分有問題,具體代碼如下:
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) # 報錯行
解決方案:
立即學(xué)習(xí)“Python免費學(xué)習(xí)筆記(深入)”;
通過仔細(xì)分析代碼,發(fā)現(xiàn)代碼中缺少對數(shù)據(jù)庫事務(wù)的處理。在數(shù)據(jù)庫操作中,特別是涉及到多個表的操作時,需要使用事務(wù)來保證數(shù)據(jù)的完整性。
修改后的代碼如下:
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() # 提交事務(wù) print('插入成功') except Exception as e: mydb.rollback() # 回滾事務(wù) print('err: ' + sql) print(e)
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END