【发布时间】:2020-01-14 09:47:34
【问题描述】:
我一直在使用 python 自动执行一些 SQL 查询,并且我一直在尝试使用 try 和 except 来捕获错误。这在大多数情况下都可以正常工作,但如果我的 SQL 语句不返回行(例如,插入到数据库中的表中),那么它会发送错误并停止脚本。
错误看起来像:
此结果对象不返回行。它已自动关闭。
有没有办法使用 case 语句或类似的语句,如果错误与上述相同,则继续运行,否则停止?
示例代码:
import time
import logging
import datetime
import sys
from datetime import timedelta
def error_logs(e):
#calculate running time
runtime = (time.time() - start_time)
#capture error messages (only using Line number)
exc_type, exc_obj, exc_tb = sys.exc_info()
#fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
line = 'Line ' + str(exc_tb.tb_lineno)
#print the error
logging.exception("Error")
message = "***ERROR***: Script Failed. "
write_logs((str(datetime.datetime.now()) + ", " + message + str(e) + ". " + line + ". Run time: " + str(round(runtime)) + " seconds." + "\n"))
def write_logs(message):
log_path = r"C:\Logs\Logs.txt"
with open(log_path, 'a+') as log:
log.write(str(datetime.datetime.now()) + ", " + message + "\n")
try:
db.query('''
insert into my_table (column1, column2, column3)
select * from my_other_table
where date = '2019-09-12'
''')
except Exception as e:
error_logs(e)
【问题讨论】:
-
这是一个引发的异常吗? 记录的消息?你在用什么图书馆?那不是有效的 Python……
-
所以
db.query引发空结果异常?我会从那里开始,这似乎是不寻常的行为。db是什么?你自己的课?一些现有的数据库适配器? – 如果无法修复该行为,那么它会引发什么类型的错误?一些不同的类型,还是通用的? -
无论 db 是什么,它都可以区分查询(可以返回行)和不能使用的“插入”语句。所以“db.query”可能只是错误的方法。
-
然后删除 try/excet 以查看完整的错误消息
-
如果
db.query()是你自己的函数,那么检查这个函数是否需要行,也许你应该添加一些if/else来解决这个问题
标签: python sql error-handling try-catch