python - psycopg2 查询没有正确解析参数?

标签 python amazon-redshift psycopg2 psql

将 python 2.7.12 与 psycopg2 版本 2.6.2 一起使用,但没有成功提交生成的查询(与我刚输入的字符串相反)。查询 AWS RedShift 实例。

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

我非常努力地按照 http://initd.org/psycopg/docs/usage.html#query-parameters 上的文档进行操作: enter image description here

我的代码是这样的:

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';

最佳答案

你有一个异常(exception)情况,稍后将在 docs 中描述。 :

Only variable values should be bound via this method: it shouldn’t be used to set table or field names. For these elements, ordinary string formatting should be used before running 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即使您信任消息来源。

关于python - psycopg2 查询没有正确解析参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370810/

相关文章:

postgresql - string_to_array 函数

sql - Redshift psql自动增加偶数

python - 2 列上的 Array_agg 输出未被识别为列表

python - 在 python 中处理 Telegram bot 的多个问题

python - 为什么 len(<a list object>) 这么慢?

python - 检查日期是否在另一个数据框中并设置一个新列

python - 从类方法中提取重复代码

sql - 将数字字段中带逗号的数据导入 redshift

python - 处理 psycopg2 中的重复字段

python - 将dict对象添加到postgresql