2011-07-28 57 views
6

我正在使用Postgres 9和Python 2.7.2以及psycopg2,並試圖插入帶正確轉義的引號的字符串值數組。示例:Postgres/psycopg2 - 插入字符串數組

metadata = {"Name": "Guest", "Details": "['One', 'Two', 'Three']"} 

cur.execute("insert into meta values ('%s');" % metadata) 

會拋出異常:

psycopg2.ProgrammingError: syntax error at or near "One" 
LINE 1: "Details": "['One... 
        ^

我也嘗試使用Postgres的E反斜槓逃脫一起,但還沒有找到正確的組合呢。想法?

+0

你用'''''''',''''''''''''''得到了什麼錯誤? – agf

回答

16

你必須讓psycopg做參數你綁定:不要試圖引用他們你自己。

Psycopg自動將python列表轉換爲postgres數組。檢查http://initd.org/psycopg/docs/usage.html

+0

啊我錯過了輕微的格式改變。使用cur.execute(「插入元值%s」,元數據)爲我工作。非常感謝你。 – Ian

0

如果你要放棄整個元數據作爲一個字符串到表中,你可以做:

cur.execute("insert into meta values (%s);", (str(metadata),)) 
0

當你要插入一個數組通過SQL一個PostgreSQL數據庫,你做這樣的:

INSERT INTO tablename VALUES ('{value1,value2,value3}'); 

注意:你需要單引號包圍的大括號!所以實際上你傳遞一個字符串/ VARCHAR一個特殊的「陣」的語法到DB

如果我輸入您的代碼到一個python解析器我得到的是這樣的:

'{'Name': 'Guest', 'Details': "['One', 'Two', 'Three']"}' 

但PostgreSQL的期望的東西像這樣:

'{"Name","Guest","Details",{"One","Two","Three"}}' 

檢查對陣列手冊:http://www.postgresql.org/docs/9.0/static/arrays.html

因此,無論您根據PostgreSQL的「數組語法格式字符串「通過編寫一個幫助函數,或者使用一個庫來爲你做。

2
def lst2pgarr(alist): 
    return '{' + ','.join(alist) + '}' 

pyarray = ['pippo', 'minni', 1, 2] 

conn = psycopg2.connection ( HERE PUT YOUR CONNECTION STRING ) 
c = conn.cursor() 

c.execute('select ... where pgarray_attr = %r' % (lst2pgarr(pyarray)) 
c.execute('insert into tab(pgarray_attr) values (%r)' % (lst2pgarr(pyarray))