I am executing a series of sql statements 1 by 1 (outputs of initial ones are relied upon later). These queries are table creations, table alterations, and view updates.
I can execute them in Python 1 by 1, but for logging purposes and safety protocols, I need to figure out how to achieve the following outcomes:
- If the query fails, obtain the response back
- Utilize try and except correctly to not disturb anything that doesn't fully execute.
Here is the code I have that works today (looping through directories and files within directories). There are some variable declarations and os directory setup prior to entering the loop here.
EDIT: The tls alias is a module of self created tools that I work with, the tls.create_lake_engine() function is simply creating an engine to connect to my sql server using sqlalchemy's create_engine method.
for file in contents:
# check if file is a sql statement or a python module
if file.endswith('.sql'):
# read the query
file_contents = open(file).read()
statements = file_contents.split(';')
print('executing {} statements from file {}'.format(
len(statements), file))
statements = [x.strip() for x in statements]
i = 0
for statement in statements:
i+=1
print('\texecuting statement {}'.format(i))
engine = tls.create_lake_engine()
conn = engine.connect()
trans = conn.begin()
conn.execute(statement)
trans.commit()