Python3程序报错“err: + sql”如何解决?
在执行如下 python 代码时,遇到了错误“err: + 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) print('插入成功') except exception as e: print('err: ' + sql) print(e)
解决方案:
引发此错误的原因是,在 sql 语句的字符串格式化过程中,将 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) print('插入成功') except Exception as e: raise Exception('err: ' + sql)
修正后的代码将异常信息作为异常抛出,而不是打印在控制台上,从而正确处理错误。