我有一个名为属性的类变量,它列出了我想在数据库中更新的实例变量:
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 ...
谢谢。
最佳答案
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)
到需要更新的数据库的任何 DB API 游标(我不知道你想使用的 WHERE 条件识别要更新的特定记录,这就是为什么我在此处放置一个 whatreveryouwanthere
占位符;-)。
关于python - 在 Python 中构建 MySQL 更新查询的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2746232/