[ACCEPTED]-psycopg2 "TypeError: not all arguments converted during string formatting-psycopg2

Accepted answer
Score: 33

The problem you have is that you are passing 4 the object as second parameter: the second 3 parameters should be either a tuple or a 2 dict. There is no shortcut as in the % string 1 operator.

You should do:

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

Encountered the same problem and found that 10 this is actually covered in their FAQ

I try 9 to execute a query but it fails with the 8 error not all arguments converted during 7 string formatting (or object does not support indexing). Why? Psycopg 6 always require positional arguments to be passed 5 as a sequence, even when the query takes 4 a single parameter. And remember that 3 to make a single item tuple in Python you 2 need a comma! See Passing parameters to 1 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
Score: 6

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

More Related questions