python mysql更新函数从元组的问题,我需要你的帮助再次
我想更新我数据库中的十分之几条条目。 我的想法如下,不幸的是,我得到以下错误 我试图转换为字符串,但它不起作用 有什么想法吗 TypeError:必须是字符串或只读缓冲区,而不是元组python mysql更新函数从元组的问题,我需要你的帮助再次,python,mysql,mysql-python,Python,Mysql,Mysql Python,我想更新我数据库中的十分之几条条目。 我的想法如下,不幸的是,我得到以下错误 我试图转换为字符串,但它不起作用 有什么想法吗 TypeError:必须是字符串或只读缓冲区,而不是元组 lookup={ 'Gigi':'Gigi Hofleitner', 'Horst':'Horst Sergio' } for i in lookup: sql="UPDATE namen SET Name = '%s' WHERE `Name` = '%s'",((lookup[i]),i) c
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)
或
对于经过消毒且可读性更强的版本:
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()
我也有同样的问题,但用这个答案解决了!
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()