views:

1268

answers:

2

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?

+3  A: 

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)
Milen A. Radev
I've been looking everywhere for the pyscopg2 manual unsuccessfully. I assumed the lib worked in a similar way to MySQLdb, but I guess it doesn't..
Ian
+1  A: 

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,))
piro