使用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「)) –