Python/psycopg2 WHERE IN statement

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

    To expland on the answer a little and to address named parameters, and converting lists to tuples:

    countryList = ['UK', 'France']
    
    sql = 'SELECT * from countries WHERE country IN %(countryList)s'
    
    cur.execute(sql, { # You can pass a dict for named parameters rather than a tuple. Makes debugging hella easier.
        'countryList': tuple(countryList), # Converts the list to a tuple.
    })
    

提交回复
热议问题