在字符串中格式化python字符串

2024-04-28 03:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python MySQL connector,需要编写一个SQL查询,如下所示:

update inventory set checked_out = 'n' where item = 'dongle'

所有项目都被放置在上一次执行的游标中,我在循环中使用:

cnx = mysql.connector.connect(host='localhost',database='mem_bug',user='root',password='July@2013')
for r in cursor :
   sql = "update inventory set checked_out = 'n' where item = {}".format(r[0])
   cursor.execute(sql)
   cnx.commit()

形成SQL时,其形式如下:

update inventory set checked_out = 'n' where item = dongle

因此给出的误差为:

_mysql_connector.MySQLInterfaceError: Unknown column 'dongle' in 'where clause'

如何在字符串中格式化字符串以正确执行SQL


Tags: insqlconnectormysqlupdateoutitemwhere
1条回答
网友
1楼 · 发布于 2024-04-28 03:00:34

只要加上引号,问题就来了:

cnx = mysql.connector.connect(host='localhost',database='mem_bug',user='root',password='July@2013')
for r in cursor :
   sql = "update inventory set checked_out = 'n' where item = '{}'".format(r[0])
   cursor.execute(sql)
   cnx.commit()

相关问题 更多 >