kon*_*art 11 python trac psycopg2
我正在尝试执行一个简单的查询,但无论我如何传递参数,都会收到此错误.
这是查询(我使用Trac db对象连接到DB):
cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
Run Code Online (Sandbox Code Playgroud)
schema和每个['id']都是简单的字符串
print("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
Run Code Online (Sandbox Code Playgroud)
结果:
SELECT name FROM "Planing".customer WHERE firm_id='135'
有错误是删除后引用firm_id=,但该方式参数被视为一个整数,并::text导致相同的错误.
Spe*_*ton 17
就我而言,我没有意识到您必须将一个元组传递给cursor.execute。我有这个:
cursor.execute(query, (id))
Run Code Online (Sandbox Code Playgroud)
但是我需要通过一个元组
cursor.execute(query, (id,))
Run Code Online (Sandbox Code Playgroud)
rsa*_*acc 10
我得到了同样的错误,并且在我的生活中无法解决如何修复,最终这是我的愚蠢错误,因为我没有足够的参数匹配元组中的元素数量:
con.execute("INSERT INTO table VALUES (%s,%s,%s,%s,%s)",(1,2,3,4,5,6))
Run Code Online (Sandbox Code Playgroud)
请注意,我在要插入表中的值中有5个元素,但在元组中有6个元素.
小智 7
你可以试试这个:
cursor.execute("INSERT INTO table_name (key) VALUES(%s)",(value1,))
Run Code Online (Sandbox Code Playgroud)
如果缺少(,)after ,您将收到错误value1。
在 SQL 命令中传递变量的正确方法是使用该execute()方法的第二个参数。我认为您应该从第二个参数中删除单引号,请在此处阅读 - http://initd.org/psycopg/docs/usage.html#the-problem-with-the-query-parameters。
请注意,您不能将表名作为参数传递给execute,这被认为是不好的做法,但有一些解决方法:使用 SQL 查询参数
将表名作为参数传递到 psycopg2
psycopg2cursor.execute() 会导致语法错误
要传递表名称,请尝试以下操作:
cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id=%s""" % (schema, '%s'), (each['id'],))
Run Code Online (Sandbox Code Playgroud)
您不应该使用字符串插值来传递数据库查询中的变量,但使用字符串插值来设置表名是正常的(只要它不是外部输入或限制允许值).尝试:
cursor.execute("""SELECT name FROM %s.customer WHERE firm_id=%%s""" % schema, each['id'])
Run Code Online (Sandbox Code Playgroud)
在对数据库进行编程之前,应该要求读取DB API使用规则.
用 AsIs
from psycopg2.extensions import AsIs
cursor.execute("""
select name
from %s.customer
where firm_id = %s
""",
(AsIs(schema), each['id'])
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18967 次 |
| 最近记录: |