Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
Ian Avatar asked Apr 27 '09 14:04

Ian


3 Answers

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,))
like image 135
piro Avatar answered Nov 18 '22 07:11

piro


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
like image 25
Salvador Dali Avatar answered Nov 18 '22 07:11

Salvador Dali


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)
like image 6
Milen A. Radev Avatar answered Nov 18 '22 06:11

Milen A. Radev