1

I'm trying to retrieve some data from a postgresql database using psycogp2, and either exclude a variable number of rows or exclude none.

The code I have so far is:

def db_query(variables):
    cursor.execute('SELECT * '
                   'FROM database.table '
                   'WHERE id NOT IN (%s)', (variables,))

This does partially work. E.g. If I call:

db_query('593')

It works. The same for any other single value. However, I cannot seem to get it to work when I enter more than one variable, eg:

db_query('593, 595')

I get the error:

psycopg2.DataError: invalid input syntax for integer: "593, 595"

I'm not sure how to enter the query correctly or amend the SQL query. Any help appreciated.

Thanks

1
  • The argument should be a list or a tuple. See initd.org/psycopg/docs/… (under "lists adaptation") Commented Oct 9, 2017 at 8:55

1 Answer 1

1

Pass a tuple as it is adapted to a record:

query = """
    select *
    from database.table
    where id not in %s
"""
var1 = 593
argument = (var1,)
print(cursor.mogrify(query, (argument,)).decode('utf8'))
#cursor.execute(query, (argument,))

Output:

select *
from database.table
where id not in (593)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @clodoaldo Neto for the response. I'm not clear on how I can adapt this so I can pass in multiple variables?
@blountdj To pass multiple variables just do argument = (var1, var2...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.