![](/img/trans.png)
[英]How to build mysql query string in more beautiful way in python?
[英]Efficient way to build a MySQL update query in Python
我有一個稱為屬性的類變量,該變量列出了要在數據庫中更新的實例變量:
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()
最后在需要更新的數據庫上的任何DB API游標上調用mycursor.execute(sql, values)
(我不知道要用於識別要更新的特定記錄的WHERE條件,這就是為什么我把whatreveryouwanthere
占位符有;-)。
第一個問題:是否將使用屬性中的所有變量? 如果是這樣,最簡單的方法可能就是使用DBAPI的execute方法。
假設您的光標實例化為csr:
sql="UPDATE mytable SET phone=? where username=?"
variables = ("a phone number","a username")
csr.execute(sql,variables)
還有其他方法,例如使用字典,位置指示符等。有關更多詳細信息,請參見DBAPI FAQ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.