Python/pg8000 WHERE IN statement

1.4k Views Asked by At

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

names = ('David', 'Isaac')
sql = 'SELECT * from names WHERE name IN %s'
cur.execute(sql,(names,))

The response in https://stackoverflow.com/a/28117658/5879128 works for psycopg2 but does not work in pg8000.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER
  1. Generate the proper number of placeholders. In pg8000 the placeholder defaults to %s.
  2. Interpolate placeholders to the query string.
  3. Execute SQL-injection-safe query.

Like so:

sql = 'SELECT * from names WHERE name IN ({})'.format( ','.join(['%s']*len(names)) )
# results in -> 'SELECT * from names WHERE name IN (%s,%s)'
cur.execute(sql,(names,))