I'd like to build an update query from a list of keys and values, only putting quotes around the values where necessary. Right now (with the below code) quotes appear around both strings and ints. How can I do this efficiently?
attributes = ['filename','filesize']
media_id = 12345
sqlbase = """UPDATE media
SET %s
WHERE media_id = %s"""
setpieces = []
values = []
setpieces.append("""timestamp_modified = %s""" % (time.time()))
#Recurse through all attributes in the class
for key in attributes:
#For each key, get the value
if key in attributes:
value = getattr(self, key, None)
setpieces.append("""%s = '%s'""" % (key, value))
query = sqlbase % (', '.join(setpieces), media_id)
Let MySQLdb decide that by passing query parameters to execute():
sqlbase = """UPDATE media
SET {query}
WHERE media_id = %(media_id)s"""
mapping = {key: getattr(self, key, None) for key in ['filename', 'filesize']}
mapping['media_id'] = 12345
setpieces = ["{key} = %({key})s".format(key=key) for key in mapping] + \
["timestamp_modified = %s" % time.time()]
cursor.execute(sqlbase.format(query=','.join(setpieces)), mapping)
As a bonus, you get escaping that would help preventing SQL injections.
Also, just a side note. As you see, manually constructing a query like this doesn't look that readable and is really fragile. This is where switching to ORM may decrease the amount of headaches and suprises, take a look, for example: Pony ORM, or sqlalchemy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With