psycopg2 "TypeError: not all arguments converted during string formatting"
I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error:
TypeError: not all arguments converted during string formatting
code:
cur.execute("""
INSERT INTO
sessions
(identity_hash, posted_on)
VALUES
(%s, NOW())
""", identity_hash)
I tried adding conn.Binary("identity_hash") to the variable before insertion, but get the same error.
The identity_hash column is a bytea.
Any ideas?
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(3)

Have you taken a look at the "examples/binary.py" script in the psycopg2 source distribution? It works fine here. It looks a bit different than your excerpt:
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)

Encountered the same problem and found that this is actually covered in their 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

The problem you have is that you are passing the object as second parameter: the second parameters should be either a tuple or a dict. There is no shortcut as in the % string operator.
You should do:
cur.execute("""
INSERT INTO
sessions
(identity_hash, posted_on)
VALUES
(%s, NOW())
""", (identity_hash,))
发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。