2009-04-27 25 views
10

我想二進制數據(一個漩渦散列)插入到PG表,我得到一個錯誤:psycopg2「類型錯誤:不是字符串格式化過程中轉換所有參數」

TypeError: not all arguments converted during string formatting 

代碼:

cur.execute(""" 
    INSERT INTO 
     sessions 
     (identity_hash, posted_on) 
    VALUES 
     (%s, NOW()) 
""", identity_hash) 

我嘗試在插入前向變量添加conn.Binary(「identity_hash」),但得到相同的錯誤。

identity_hash列是一個bytea。

任何想法?

回答

6

你看過psycopg2源碼分發中的「examples/binary.py」腳本嗎?它在這裏很好。它看起來比你的摘錄有點不同:

data1 = {'id':1, 'name':'somehackers.jpg', 
    'img':psycopg2.Binary(open('somehackers.jpg').read())} 

curs.execute("""INSERT INTO test_binary 
       VALUES (%(id)s, %(name)s, %(img)s)""", data1) 
+0

我一直在到處尋找的pyscopg2手動失敗。我假定lib以類似於MySQLdb的方式工作,但我想它不會...... – Ian 2009-04-27 16:16:57

+0

從手冊:「對於位置變量綁定,第二個參數必須* always *是一個序列,即使它包含單個變量*請記住,Python需要用逗號來創建單個元素元組*「 - http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries – Ben 2017-07-13 14:30:25

19

你的問題是要傳遞的對象作爲第二個參數:第二個參數應該是一個元組或字典。在%字符串運算符中沒有捷徑。

你應該這樣做:

cur.execute(""" 
    INSERT INTO 
     sessions 
     (identity_hash, posted_on) 
    VALUES 
     (%s, NOW()) 
""", (identity_hash,)) 
7

遇到同樣的問題,發現這實際上是涵蓋在其FAQ

I try to execute a query but it fails with the error not all arguments converted during string formatting (or object does not support indexing). Why? Psycopg always require positional arguments to be passed as a sequence, even when the query takes a single parameter. And remember that to make a single item tuple in Python you need a comma! See Passing parameters to SQL queries.

cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG 
cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG 
cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct 
cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct 
相關問題