使用关键字参数作为函数输入更改sqlite3表中的信息,如何在Python中执行此操作?

时间:2017-04-11 02:24:46

标签: python mysql sqlite

关键字参数是idx,name和 passwd文件。要将索引3的记录更新为名称“Brian”,该方法称为 更新(idx = 3,name ='Brian')。如果参数idx不存在,则该方法返回False。也可以存在密码,并且使用给定值更新具有索引的记录 对于田野。

我尝试过这样的事情,但是得到一个str对象不可调用的错误,我试图在这里查看其他脚本,但我一直在收到错误。

def update(self, **kwargs):
    ''' keyword arguments are idx, name and password.
     For example, to update the record with index 3 to
     the name ’Brian’, the method is called as
     update(idx=3, name=’Brian’). The method returns
     False if the parameter idx is absent. In addition
     to name, also the passwd may be present and the record
     with the index is updated with the given values
     for the fields. The method update returns True if the
     updates succeeded, or False otherwise.'''

    if 'idx' in kwargs:

        query = 'UPDATE players set name = ?, password = ? WHERE idx = ?' (kwargs['name'], kwargs['password'],kwargs['idx'])

        self.cr.execute(query)

        self.db.commit()

        print('records updated')

        return True

    else:

        print('records failed to update')

        return False

1 个答案:

答案 0 :(得分:1)

你不能像你已经完成的那样把参数放在查询中:

query = 'UPDATE players set name = ?, password = ? WHERE idx = ?' (kwargs['name'], kwargs['password'],kwargs['idx'])

Python会认为你正试图调用该字符串文字,就像它是一个函数一样。

相反,在执行查询时传递args,因为execute()方法实际上是将值填充到SQL语句中。

query = 'UPDATE players set name = ?, password = ? WHERE idx = ?'
self.cr.execute(query, (kwargs['name'], kwargs['password'], kwargs['idx']))

更好的方法是使用命名占位符;然后你可以传递kwargs,而不必挖出你想要的字段:

query = 'UPDATE players set name = :name, password = :password WHERE idx = :idx'
self.cr.execute(query, kwargs)

要回答评论中的问题,您可以通过迭代字典,根据您拥有值的字段动态创建查询:

assert "idx" in kwargs   # idx is a required field
query = "UPDATE players SET"
for field in kwargs:
    if field != "idx":
        query += " {f} = :{f},".format(f=field)
query = query.strip(",")   # strip off unneeded comma after last field
query += " WHERE idx = :idx"
self.cr.execute(query, kwargs)

或者作为单一陈述:

query = "UPDATE players SET " + ", ".join(f + " = :" + f 
         for f in kwargs if f != "idx") + " WHERE idx = :idx"