Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct a MySQL update query in Python that only puts quotes around strings not numbers

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)
like image 890
ensnare Avatar asked Feb 07 '26 10:02

ensnare


1 Answers

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.

like image 70
alecxe Avatar answered Feb 09 '26 00:02

alecxe