Python/psycopg2 WHERE IN statement

前端 未结 3 1340
忘掉有多难
忘掉有多难 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:05

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

提交回复
热议问题