2017-01-26 1 views
3

私はpsycopg2を使用してPython 3でPostgreSQLデータベースにアクセスしています。リストに名前が入っているすべてのユーザを選択するクエリを作成しようとしています。の場合はです。提供されたリストが空の場合、その名前に関係なくすべてのユーザーを選択するという条件を無視します。値がリストにあるかどうか、またはリストが空であるかどうかをチェックする方法?

私はすでに、次の3つの呼び出し試してみた:

# 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 

上記の場合eパラメータis nullは、条件を満たす行のみが返されます。

Psycopgは、Python listをPostgresql arrayに適合させます。

parameter = [] or None 

:空のPython listからはPostgreSQL nullに適合されたPythonのNoneを取得する

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

:Postgresqlのarray値のいずれかが特定の値と等しいかどうかを確認します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'を使用することが実現していない、今は本当に愚かな感じそれは存在し、すべて...しかし、これは素晴らしい仕事、助けてくれてありがとう! :) –

関連する問題