Python/psycopg2 WHERE IN statement

前端 未结 3 1372
忘掉有多难
忘掉有多难 2020-12-13 05:44

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

# using psycopg2
countryList=[\'UK\',\'France\']

sql=\'S         


        
3条回答
  •  盖世英雄少女心
    2020-12-13 06:19

    You could use a python list directly as below. It acts like the IN operator in SQL and also handles a blank list without throwing any error.

    data=['UK','France']
    sql='SELECT * from countries WHERE country = ANY (%s)'
    cur.execute(sql,(data,))
    

    source: http://initd.org/psycopg/docs/usage.html#lists-adaptation

提交回复
热议问题