Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/psycopg2 WHERE IN statement

What is the correct method to have the list (countryList) be available via %s in the SQL statement?

# using psycopg2 countryList=['UK','France']  sql='SELECT * from countries WHERE country IN (%s)' data=[countryList] cur.execute(sql,data) 

As it is now, it errors out after trying to run "WHERE country in (ARRAY[...])". Is there a way to do this other than through string manipulation?

Thanks

like image 487
Matt Avatar asked Jan 23 '15 19:01

Matt


People also ask

How fetch data from PostgreSQL database in Python?

You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2. The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.

What is the use of psycopg2?

Using the Error class of Psycopg2, we can handle any database error and exception while working with PostgreSQL from Python. Using this approach, we can make our application robust. The error class helps us to understand the error in detail. It returns an error message and error code if any.

What is psycopg2 in Python?

Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command.


1 Answers

For the IN operator, you want a tuple instead of list, and remove parentheses from the SQL string.

# using psycopg2 data=('UK','France')  sql='SELECT * from countries WHERE country IN %s' cur.execute(sql,(data,)) 

During debugging you can check that the SQL is built correctly with

cur.mogrify(sql, (data,)) 
like image 120
Bryan Avatar answered Sep 20 '22 08:09

Bryan