【问题标题】:Formatting python string within a string在字符串中格式化python字符串
【发布时间】:2018-11-24 06:50:00
【问题描述】:

我正在使用 Python MySQL 连接器,需要编写一个 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。

【问题讨论】:

标签: python string-formatting mysql-python


【解决方案1】:

只要加引号就可以了,看来问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2010-10-05
    相关资源
    最近更新 更多