I've been automating some SQL queries using python and I've been experimenting with try and except to catch errors. This works fine most of the time but if my SQL statement doesn't return rows (e.g. inserting into a table on the database) then it sends an error and stops the script.
The error looks like:
This result object does not return rows. It has been closed automatically.
Is there a way to use a case statement or similar so that if the error is the same as the above, it continues on running, otherwise it stops?
Sample code:
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)