3

我想从键和值列表构建一个更新查询,只在必要时在值周围加上引号。现在(使用下面的代码)引号出现在字符串和整数周围。我怎样才能有效地做到这一点?

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)
4

1 回答 1

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 ORMsqlalchemy

于 2014-06-23T13:50:14.473 回答