【问题标题】:psycopg2 query not parsing parameters properly?psycopg2 查询未正确解析参数?
【发布时间】:2017-05-13 06:05:39
【问题描述】:

将 python 2.7.12 与 psycopg2 版本 2.6.2 一起使用,但未能成功提交生成的查询(而不是我刚刚输入的字符串)。针对 AWS RedShift 实例进行查询。

当我尝试运行代码时发生的情况是它失败了,因为添加了一个无关的括号(当我使用 (%s) 构造时......或者如果我只使用 %s 则添加一个额外的单引号) .我已经尝试非常仔细地遵循文档,并且还在这里和谷歌搜索过,但一无所获。有没有人对如何解决这个问题有任何建议?

我非常努力地关注http://initd.org/psycopg/docs/usage.html#query-parameters 的文档:

我的代码如下所示:

con = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=password)
cur = con.cursor()

try3 = "TRUNCATE TABLE (%s);"
values = ("schema_one.tbl_six",)
cur.execute(try3,values)

try4 = "TRUNCATE TABLE %s;"
values = ("schema_four.tbl_four",)
cur.execute(try4,values)  

产生这个输出:

$ ./test_qry.py
Traceback (most recent call last):
  File "./test_qry.py", line 23, in <module>
    cur.execute(try3,values)
psycopg2.ProgrammingError: syntax error at or near "("
LINE 1: TRUNCATE TABLE ('schema_one.tbl_six');

$ ./test_qry.py
Traceback (most recent call last):
  File "./test_qry.py", line 28, in <module>
    cur.execute(try4,values)
psycopg2.ProgrammingError: syntax error at or near "'schema_four.tbl_four'"
LINE 1: TRUNCATE TABLE 'schema_four.tbl_four';

【问题讨论】:

  • 您使用的模式假定将修改 FIELD/VALUES 对。该模式是否适用于具有 FIELD/VALUE 对的 INSERT 语句?想也许你不能像你正在尝试的那样将这个范式用于一个单一的陈述......?
  • 如果向下滚动,您可以看到展示此范例的示例代码: # 执行命令:这将创建一个新表 >>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") # 传递数据以填充查询占位符并让 Psycopg 执行 # 正确的转换(不再有 SQL 注入!) >>> cur.execute("INSERT INTO test (num, data) VALUES ( %s, %s)", ... (100, "abc'def"))

标签: python amazon-redshift psycopg2 psql


【解决方案1】:

您有一个例外情况,稍后将在 docs 中描述:

只能通过这种方法绑定变量值:不应该 用于设置表名或字段名。对于这些元素,普通字符串 在运行 execute() 之前应该使用格式化。

换句话说,你不能参数化表名或列名,必须使用字符串格式:

query = "TRUNCATE TABLE %s;"
values = ("schema_one.tbl_six",)
cur.execute(query % values)

或者,str.format():

query = "TRUNCATE TABLE {table_name};"
cur.execute(query.format(table_name="schema_one.tbl_six"))

也就是说,即使您信任来源,您仍然应该小心并验证/转义表名以防止SQL injection attacks。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多