Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python构建MySQL更新查询的有效方法_Python_Mysql_Pylons - Fatal编程技术网

用Python构建MySQL更新查询的有效方法

用Python构建MySQL更新查询的有效方法,python,mysql,pylons,Python,Mysql,Pylons,我有一个名为attributes的类变量,它列出了我要在数据库中更新的实例变量: attributes = ['id', 'first_name', 'last_name', 'name', 'name_url', 'email', 'password', 'password_salt', 'picture_id'] 每个类属性都会在实例化时更新 我希望遍历每个属性,并以以下形式构建一个MySQL更新查询: UPDATE members SET id = self.

我有一个名为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 ...

谢谢。

第一个问题:是否会使用属性中的所有变量?如果是这样,最简单的方法可能是使用DBAPI的execute方法

假设您的光标被实例化为csr:

sql="UPDATE mytable SET phone=? where username=?"
variables = ("a phone number","a username")
csr.execute(sql,variables)
还有其他方法,例如使用字典、位置指示器等。。有关更多详细信息,请参阅

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
调用者需要适当地构建一个class
Ic
对象,然后执行以下操作

sql, values = theobj.updater()

最后调用
mycursor.execute(sql,values)
在需要更新的数据库中的任何DB API游标上执行(我不知道要在哪里使用条件来标识要更新的特定记录,这就是为什么我在那里放了一个
whatreyouwanthere
占位符;-)。

嗨,Alex--谢谢。如何修改此代码以同时包含“WHERE id=123”。。。理想情况下,sqlbase应为:sqlbase='UPDATE members SET%s,其中id=%s',但我不确定如何处理第二个%s以替换为id。谢谢@诱捕,如果你的
whateyouwanthere
有一个
id=?
,将你想要的
id
值附加到
值中(在
for
循环之后,在
返回之前)。在正常值替换工作正常的情况下使用
%s
没有任何意义!