Skip to content

Instantly share code, notes, and snippets.

@horken7
Last active July 18, 2017 16:11
Show Gist options
  • Save horken7/958087175ffc873d7bea9eec7117e02d to your computer and use it in GitHub Desktop.
Save horken7/958087175ffc873d7bea9eec7117e02d to your computer and use it in GitHub Desktop.
Python execute SQL file
def exec_sql_file(self, cursor, sql_file):
"""
Function that executes an SQL script file. Executed query by query by looking through the file and adding
elements to 'statement' until if finds the delimiter symbol ';', whilst ignoring comments and
stripping space, tab and newline characters.
:param cursor: cursor, connected to correct database
:param sql_file: string, file location
:return: void
"""
print("\n[INFO] Executing SQL script file: '%s'" % (sql_file))
statement = ""
for line in open(sql_file):
line = line.strip('\n')
line = line.strip('\t')
line = line.strip('\\')
if line.strip().startswith('--'): # ignore sql comment lines
continue
if not line.strip().endswith(';'): # keep appending lines that don't end in ';'
statement = statement + line
else: # when you get a line ending in ';' then exec statement and reset for next statement
statement = statement + line
try:
cursor.execute(statement)
except (KeyError) as e:
print("\n[WARN] MySQLError during execute statement \n\tArgs: '%s'" % (str(e.args)))
statement = ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment