使用python 2.7.12与psycopg2版本2.6.2并没有成功提交生成的查询(与我刚输入的字符串相反)。查询AWS RedShift实例。psycopg2查询不正确解析参数?
当我尝试运行发生的事情是因为添加的外来括号失败代码(当我使用(%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“)) –