元组问题的python mysql更新功能,我再次需要您的帮助 [英] python mysql update function from tuple issue, I need your help again
本文介绍了元组问题的python mysql更新功能,我再次需要您的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更新数据库中十分之几的条目. 我的想法如下,很遗憾,出现以下错误.
I would like to update several 10th of entries in my database. My idea is as follows, unfortunately, I get the following error.
我试图将其转换为字符串,但是它不起作用.
I tried to convert to a string, but it does not work.
有什么主意吗?
TypeError:必须是字符串或只读缓冲区,而不是元组
TypeError: must be string or read-only buffer, not tuple
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()
推荐答案
cursor.execute()
期望一个sql语句(作为字符串)和一个可选的值序列,因此应该是:
cursor.execute()
expects a sql statement (as string) and an optional sequence of values, so it should have been either:
# 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))
对于经过清理和可读性更高的版本:
For a sanitized and more readable version:
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()
这篇关于元组问题的python mysql更新功能,我再次需要您的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文