2017-01-26 1 views
3

psycopg2을 사용하여 Python 3을 통해 PostgreSQL 데이터베이스에 액세스하고 목록이 비어 있지 않은 경우 의 이름을 가진 모든 사용자를 선택하려는 쿼리를 시도하고 있습니다.. 제공된 목록이 비어있는 경우 조건을 무시 (예 : 이름에 관계없이 모든 사용자 선택)하고 싶습니다.값이 목록에 있는지 또는 목록이 비어 있는지 확인하는 방법?

# Using list 
cursor.execute(
    "SELECT age FROM user WHERE %(names) = '{}' OR user.name IN %(names)s", 
    {'names': []}, 
) 

# Using tuple 
cursor.execute(
    "SELECT age FROM user WHERE %(names) =() OR user.name IN %(names)s", 
    {'names':()}, 
) 

# Using both list and tuple 
cursor.execute(
    "SELECT age FROM user WHERE %(names_l) = '{}' OR user.name IN %(names_t)s", 
    {'names_l': [], 'names_t':()}, 
) 

그러나 그들은 모두 한 지점에서 잘못된 구문 오류가 발생하거나 다른 :

은 이미 다음과 같은 세 가지 통화를 시도했습니다 당신은 SQL을 원하는 선택적 매개 변수에 대한

# Using list 
psycopg2.ProgrammingError: syntax error at or near "'{}'" 
LINE 17:   user.name IN '{}' 

# Using tuple 
psycopg2.ProgrammingError: syntax error at or near ")" 
LINE 16:  () ==() 

# Using both list and tuple 
psycopg2.ProgrammingError: syntax error at or near ")" 
LINE 17:   user.name IN() 

답변

2

where 절은 다음과 같습니다.

where column = :parameter or :parameter is null 

위의 경우 매개 변수 is null은 조건을 충족시키는 행만 반환합니다.

Psycopg는 Python list을 Postgresql array에 맞 춥니 다. PostgreSQL의 array 값 중 하나가 소정의 값과 동일한 지 확인하는 방법 :

parameter = [] or None 

:

where column = any (array[value1, value2]) 

빈 파이썬 list에서 PostgreSQL의 null하도록되어 파이썬 None를 얻을하려면 dictionarycursor.execute 메소드에 전달하면 매개 변수 인수에서 매개 변수 반복을 피할 수 있습니다.

names = ['John','Mary'] 

query = """ 
    select age 
    from user 
    where user.name = any (%(names)s) or %(names)s is null 
""" 
print (cursor.mogrify(query, {'names': names or None}).decode('utf8')) 
#cursor.execute(query, {'names': names or None}) 

출력 :

select age 
from user 
where user.name = any (ARRAY['John', 'Mary']) or ARRAY['John', 'Mary'] is null 

목록이 비어있는 경우 :

select age 
from user 
where user.name = any (NULL) or NULL is null 

http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

+0

내가 지금 정말 바보 같은 느낌이 나는 알지 못했다하더라도 내가 SQL의'NULL'을 사용할 수 몰랐어요 그것은 존재하고 모두 ... 그러나 이것은 도움을 주셔서 감사합니다. :) –

관련 문제