programing

Python/psycopg2 WHERE IN 문

iphone6s 2023. 8. 10. 18:34
반응형

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

psycopg3 문제가 중복으로 표시되었으니 여기에 답을 추가하겠습니다.

싸이코그3에서, 당신은 사용할 수 없습니다.in %s사이코그2에서처럼 튜플로 말입니다.대신 사용해야 합니다.ANY()목록을 다른 목록으로 감습니다.

conn.execute("SELECT * FROM foo WHERE id = ANY(%s)", [[10,20,30]])

문서: https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#you-cannot-use-in-s-with-a-tuple

언급URL : https://stackoverflow.com/questions/28117576/python-psycopg2-where-in-statement

반응형