You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作PostgreSQL时使用变量触发TypeError错误,求解决

问题解决方法

错误原因

你调用cur.execute()时传了3个独立参数,但这个方法最多只接受2个参数:第一个是完整的SQL语句模板,第二个是包含变量的序列(元组/列表)或字典。

正确写法(推荐)

使用psycopg2的参数化查询(同时避免SQL注入风险),注意user是PostgreSQL关键字,需要用双引号包裹:

conn = psycopg2.connect("dbname=postgres user=postgres password=postgres")
cur = conn.cursor()

# 用%s作为占位符,参数放在元组里传递
cur.execute("SELECT password FROM \"user\" WHERE email = %s;", (inputed_email,))
print(cur.fetchone())
        
cur.close()
conn.close()

其他实现方式

如果涉及多个变量,用字典形式传递参数会更直观:

cur.execute("SELECT password FROM \"user\" WHERE email = %(email)s;", {"email": inputed_email})

重要提醒

  • 绝对不要直接拼接SQL字符串(比如"SELECT ... WHERE email = '" + inputed_email + "'"),这会引发严重的SQL注入漏洞。
  • 当表名/列名是PostgreSQL关键字时,必须用双引号包裹,否则会触发语法错误。

内容的提问来源于stack exchange,提问作者Ed1441

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:14:56