Search code examples
pythonpostgresqlpsycopg2

How to insert variables into python when using PostgreSQL


So I'm sure there is already a solution out there for my question but I haven't been able to see an answer that helps me understand it clearly.

I want to use a function that takes in a variable and uses that variable in a PostgreSQL select statement.

This is my attempt which is incorrect.

def some_func(var):
    cursor.execute("SELECT * FROM table WHERE attribute = %s",var)
    return

So if I am to run some_func("height"), I want the postgres statement to be executed as follows:

SELECT * FROM table WHERE attribute = 'height';

I got the error:

TypeError: not all arguments converted during string formatting

Solution

  • Per the documentation

    Parameters may be provided as sequence or mapping and will be bound to variables in the operation.

    Place the variable in a sequence:

    cursor.execute("SELECT * FROM table WHERE attribute = %s", [var])
    

    Read also Passing parameters to SQL queries.