python - psycopg2如何处理TypeError : not all arguments converted during string formatting

标签 python postgresql psycopg2

我有一个简单的数据库查询,由 psycopg2 但我不知道为什么它总是显示错误 这是代码

ip ="127.0.0.1"
 sql="select count(*) from radacct where nasipaddress=%s"
 cur.execute(sql,ip)

然后会显示

TypeError: 并非所有参数都在字符串格式化期间转换

如果我这样尝试

cur.execute("select count(*) from radacct where nasipaddress=%s" % ip)

还是不行

我怎样才能以正确的方式将参数传递给 psycopg2。请帮助我!

最佳答案

传递给 execute 的 sql 参数必须在元组或列表中,即使只有其中之一。这在 documentation 中有说明。 :

For positional variables binding, the second argument must always be a sequence, even if it contains a single variable. And remember that Python requires a comma to create a single element tuple:

所以你需要这样做:

ip ="127.0.0.1" 
sql="select count(*) from radacct where nasipaddress=%s"
cur.execute(sql, (ip,))

关于python - psycopg2如何处理TypeError : not all arguments converted during string formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292409/

相关文章:

python - psycopg2 只显示 Postgresql 数据库的第一行

python - Django的classonlymethod有什么用?

python - AppRegistryNotReady : Apps aren't loaded yet. Django

postgresql - 如何永久关闭postgres的自动提交

postgresql - 在 FROM 中使用 JOIN 语句的别名

postgresql - Postgres 不区分大小写的排除约束

postgresql - 如何在 Python 中使用 psql "\copy"?

python - 删除或更改列表中的特定重复元素(并非所有重复元素)

python - 为什么我的标签和条目在 python tkinter 中不可见?

python - 使用新列(时间序列技术指标)动态更新现有的 Postgres 表 (psycopg2)