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

时间:2018-11-24 06:50:00

标签: python string-formatting mysql-python

我正在使用Python MySQL连接器,需要将SQL查询编写为:

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

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

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。

1 个答案:

答案 0 :(得分:0)

只需添加引号就可以解决问题:

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()