简体   繁体   English

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

[英]Formatting python string within a string

I am using Python MySQL connector, need to write a SQL query as: 我正在使用Python MySQL连接器,需要将SQL查询编写为:

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

All the items are placed in a Cursor from a previous execution, i'm using in a loop as : 所有项目都放置在上一次执行的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()

When SQL is formed it is formed as : 形成SQL时,其形式为:

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

Hence gives the error as : 因此给出错误为:

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

How can I format string within the string to get my SQL rightly executed. 如何格式化字符串中的字符串以正确执行我的SQL。

Just add quotation mark and it seems the problem: 只需添加引号,似乎是问题所在:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM