我想更新数据库中的第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()
解决方法:
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()
标签:python,mysql,mysql-python
来源: https://codeday.me/bug/20190831/1774751.html