在Python中高效构建MySQL更新查询的方法

1 投票
2 回答
885 浏览
提问于 2025-04-15 22:12

我有一个叫做 attributes 的类变量,它列出了我想要在数据库中更新的实例变量:

attributes = ['id', 'first_name', 'last_name', 'name', 'name_url',
              'email', 'password', 'password_salt', 'picture_id']

每当创建这个类的实例时,这些类属性都会被更新。

我想要遍历每一个属性,并构建一个 MySQL 更新查询,格式如下:

UPDATE members SET id = self._id, first_name = self._first name ...

谢谢。

2 个回答

0

第一个问题:属性中的所有变量都会被使用吗?如果是这样,最简单的方法可能就是使用数据库API的执行方法。

假设你的游标被命名为csr:

sql="UPDATE mytable SET phone=? where username=?"
variables = ("a phone number","a username")
csr.execute(sql,variables)

还有其他方法可以做到,比如使用字典、位置指示符等等。想了解更多细节,可以查看DBAPI FAQ

3
class Ic(object):
  attributes = ['id', 'first_name', 'last_name', 'name', 'name_url',
              'email', 'password', 'password_salt', 'picture_id']

  def __init__(self): ...

  # and other methods that set all the attributes on self

  def updater(self):
    sqlbase = 'UPDATE members SET %s WHERE whateveryouwanthere'
    setpieces = []
    values = []
    for atr in self.attributes:
      setpieces.append('%s = ?' % atr)
      values.append(getattr(self, atr, None))
    return sqlbase % ', '.join(setpieces), values

调用者需要正确地创建一个 Ic 类的对象,然后执行

sql, values = theobj.updater()

最后,调用 mycursor.execute(sql, values),这个调用是针对需要更新的数据库的某个数据库API游标(我不知道你想用什么条件来确定具体要更新的记录,所以我在这里放了一个 whatreveryouwanthere 的占位符;-)。

撰写回答