从元组问题python mysql更新功能,我需要你的帮助

时间:2013-11-23 12:48:49

标签: python mysql mysql-python

我想更新数据库中的第10个条目。 我的想法如下,遗憾的是,我收到以下错误。

我尝试转换为字符串,但它不起作用。

有什么想法吗?

TypeError:必须是字符串或只读缓冲区,而不是元组

lookup={
'Gigi':'Gigi Hofleitner',
'Horst':'Horst Sergio'
}

for i in lookup:
    sql="UPDATE namen SET Name = '%s' WHERE `Name` = '%s'",((lookup[i]),i)
    cursor.execute(sql)
    connection.commit()

1 个答案:

答案 0 :(得分:5)

cursor.execute()需要一个sql语句(作为字符串)和一个可选的值序列,所以它应该是:

# this build a (statement, (values,....)) tuple
args = "UPDATE namen SET Name = '%s' WHERE `Name` = '%s'",(lookup[i],i)

# so you need positional arguments unpacking:
cursor.execute(*args) 

sql = "UPDATE namen SET Name = '%s' WHERE `Name` = '%s'"
cursor.execute(sql, (lookup[i],i))

对于经过消毒和更易阅读的版本:

lookup={
    'Gigi':'Gigi Hofleitner',
    'Horst':'Horst Sergio'
}

# no need to create the same invariant string again and agin
sql="UPDATE namen SET Name=%s WHERE Name=%s"

for oldname, newname in lookup.items():
    cursor.execute(sql, (newname, oldname))

# better to commit only once    
connection.commit()