I'm generating SQL statements to be used in updating records in an existing database. I'm using pymssql as my db api. Is there any way to make this code more pythonic?
def update_statement(table, keys:list, data:dict):
"""
This function takes a table name, the keys for the table, and a dictiary for the record to be updated into the table.
A string representing the SQL statement to be used in the session is returned.
:param table: The name of the table to be updated.
:param keys: The primary key/ keys for the table.
:param data: A dictionary representing the data that is to be updated against.
:return: The return value is a string representing the SQL statement to be used in the session.
"""
h = 'UPDATE {} SET'.format(table)
# Generate SET Clauase
for key, value in data.items():
if key in keys:
continue
else:
c = '{} = {},'.format(key, value)
h = ' '.join([h, c])
h = h.strip(',')
h = ' '.join([h, 'WHERE'])
# Generate WHERE clause
for key in keys:
h = ' '.join([h, '{} = {}'.format(key, data[key])])
h = ''.join([h, ','])
h = h.strip(',')
# Add closing semicolon.
h = ''.join([h, ';'])
# Return sql statement
return h
I was wanting to implement the Template class from the string module, but couldn't figure out a way to be able to pass in an iterable number of variables to a template and add a comma to the end of each iteration (except for the last iteration).