[python] Python / psycopg2 WHERE IN 문

SQL 문에서 % s를 통해 목록 (countryList)을 사용할 수있는 올바른 방법은 무엇입니까?

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

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

지금처럼 “WHERE country in (ARRAY […])”를 실행하려고하면 오류가 발생합니다. 문자열 조작 이외의 다른 방법이 있습니까?

감사



답변

를 들어 IN운영자, 당신은 원하는 튜플 대신 목록 SQL 문자열에서, 그리고 제거 괄호.

# using psycopg2
data=('UK','France')

sql='SELECT * from countries WHERE country IN %s'
cur.execute(sql,(data,))

디버깅하는 동안 다음을 사용하여 SQL이 올바르게 빌드되었는지 확인할 수 있습니다.

cur.mogrify(sql, (data,))


답변

대답을 조금 설명하고 명명 된 매개 변수를 처리하고 목록을 튜플로 변환하려면 다음을 수행하십시오.

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.
})


답변

아래와 같이 파이썬 목록을 직접 사용할 수 있습니다. SQL에서 IN 연산자처럼 작동하며 오류없이 빈 목록을 처리합니다.

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

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


답변