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
相关产品推荐
相关产品推荐

