Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Psycopg2 - not all arguments converted during string formatting

I'm trying to insert the value of the variable test_text into a Postgres 9.6 database, each time the database_insert function is triggered.

I'm using Python 3.6 and psycopg2 v 2.7

If I use the below code without the placeholder: e.g replace %s with 'test' and remove , (test_text) - it works as I would expect...

def database_insert(update):

    test_text = 'This is some test text'

    with psycopg2.connect("DB CONNECTION DETAILS ARE HERE'") as conn:

        cur = conn.cursor()

        cur.execute("INSERT INTO test VALUES(%s);", (test_text))

        conn.commit()

        cur.close()

    conn.close()

However when the function trys to insert the value of the test_text variable using the %s placeholder, I get the error below...

cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting

Any help on where I am going wrong with this will be much appreciated!

like image 671
Mark Smith Avatar asked Dec 23 '17 22:12

Mark Smith


People also ask

How do you fix not all arguments converted during string formatting?

The Python "TypeError: not all arguments converted during string formatting" occurs when we use incorrect syntax to format a string or use the % operator with a string and a number. To solve the error, call the format() method on the string and provide values for all placeholders.

Is Psycopg2 asynchronous?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY. Please refer to the PostgreSQL documentation for examples about how to use this form of communication.

Is Psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors. In DB API 2.0 parlance, Psycopg is level 2 thread safe.

What is Psycopg cursor?

class cursor. Allows Python code to execute PostgreSQL command in a database session. Cursors are created by the connection. cursor() method: they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection.


1 Answers

There's a subtle issue here.

You need a comma to make a tuple not just the parens/brackets.

So simply change to:

cur.execute("INSERT INTO test VALUES(%s);", (test_text,))

And you should be good!

like image 164
mechanical_meat Avatar answered Sep 24 '22 18:09

mechanical_meat