psycopg2如何处理TypeError:不是在格式化字符串时转换所有参数 [英] psycopg2 how deal with TypeError: not all arguments converted during string formatting

查看:98
本文介绍了psycopg2如何处理TypeError:不是在格式化字符串时转换所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a simple database query by psycopg2 but i do not know why it always show errors here is the code

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

然后它将显示

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

TypeError: not all arguments converted during string formatting

,如果我尝试这种方式

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

it仍然无法正常工作

it is still not working

我如何以正确的方式将参数传递给psycopg2。请帮助我!

how can i pass the parameters to psycopg2 in the correct way.please help me!

推荐答案

您传递给 execute 的sql参数必须位于元组或列表中,即使其中只有一个。这在文档中进行了说明:

The sql arguments you pass to execute must be in a tuple or list, even if there's only one of them. This is noted in the documentation:


对于位置变量绑定,第二个参数必须始终是
序列,即使它包含单个变量也是如此。记住
Python需要一个逗号来创建单个元素元组:

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

这篇关于psycopg2如何处理TypeError:不是在格式化字符串时转换所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆