我有一个简单的数据库查询,由 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/