python - 如何解决Python错误 "not all arguments converted while string formatting"

标签 python arguments string-formatting

当我执行下面的程序时

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

效果很好。但是,当我尝试在查询中添加参数时,如下所示

import MySQLdb
 cn = MySQLdb.connect(host="localhost", user="root", passwd="****",     
db="sv_data")
cursor = cn.cursor()

a="10011"
cursor.execute("select addressline1, zipcode from sv_address where zipcode = 
%s", (a))
for (addressline1, zipcode) in cursor:
 print(addressline1, zipcode)

cursor.close()
cn.close()

出现错误ProgrammingError:在字符串格式化过程中并非所有参数都被转换

您能告诉我如何解决这个问题吗?我尝试了各种选择。 zipcode 是 mysqldb 中的 varchar 字段

最佳答案

您没有传递参数。你宁愿给它一个字符串。

试试这个。

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

最好的方法是将参数和 sql_query 分开

_sql = "select addressline1, zipcode from sv_address where zipcode = {0}"
cursor.execute(_sql.format(a))

关于python - 如何解决Python错误 "not all arguments converted while string formatting",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45647026/

相关文章:

Python:用字典项中所有可能的值替换每个字母

python - 如何将列表发送到 Azure Durable Functions

python - 无法在 tensorflow keras中附加张量板回调

bash - 在 Bash 中,是否可以编写一个 'identity' 函数(相对于参数传递/返回)

c - 用可变数量的参数包装宏

java - 如何按空格格式化文本?

python - tkinter 左键单击 GUI 中的 TAB。如何检测用户何时执行此操作

objective-c - 带有 NS_REQUIRES_NIL_TERMINATION 的多参数列表

JavaScript Chart.js - 显示在工具提示上的自定义数据格式

java - 使用 DecimalFormat 格式化 Double 以在没有科学记数法的情况下打印