如何解决python错误“字符串格式化时未转换所有参数”

2024-03-28 08:01:26 发布

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

当我执行下面的程序时

import MySQLdb
cn = MySQLdb.connect(host="localhost", user="root", passwd="mysqlroot", 
db="sv_data")
cursor = cn.cursor()
cursor.execute("select addressline1, zipcode from sv_address where zipcode = '10011'")
for (addressline1, zipcode) in cursor:
print(addressline1, zipcode)
cursor.close()
cn.close()

它工作得很好。但是当我尝试在查询中添加参数时,如下所示

^{pr2}$

获取错误编程错误:在字符串格式化过程中并非所有参数都已转换

你能告诉我怎么解决这个问题吗。我试过各种选择。zipcode是mysqldb中的varchar字段


Tags: import程序localhosthostclose参数connect错误
2条回答

你没有通过辩论。你是在给它一根绳子。在

试试这个。在

cursor.execute("select addressline1, zipcode from sv_address where zipcode = %s" % a )

最好的方法是分离参数和sql_query

^{pr2}$

我认为问题在于cursor只是将(a)读作一个字符串,并在其中看到多个未被转换的值(1, 0, 0, 1, 1)。所以如果你加上一个逗号:

cursor.execute("select addressline1, zipcode from sv_address where zipcode = %s", (a,))

我相信这会起作用的。在

例如,看看这个函数和结果:

^{pr2}$

参数不是作为元组读取的,而是作为字符串读取的。在

相关问题 更多 >