我想从键和值列表中构建更新查询,只在必要时在值周围加上引号。现在(使用下面的代码)引号出现在字符串和整数周围。我怎样才能有效地做到这一点?
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)
答案 0 :(得分:2)
让MySQLdb
通过将查询参数传递给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)
作为奖励,您可以逃避,这有助于防止SQL注入。
另外,只是旁注。如您所见,手动构建这样的查询看起来并不可读,而且非常脆弱。这是切换到ORM
可能会减少头痛和惊喜的地方,例如:Pony ORM
或sqlalchemy
。