pythonwhere-inpython-db-apipg8000

Python/pg8000 WHERE IN statement


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!


Solution

    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,))