postgresql
  • list
  • parameters
  • psycopg2
  • where-in
  • 2017-01-26 135 views 3 likes 
    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':()}, 
    ) 
    

    但他們都拋出一個無效的語法錯誤,從一個點或另一個:

    # 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

    可選參數,你想要一個SQL where子句如:

    where column = :parameter or :parameter is null 
    

    與上面的那樣當th e參數is null將返回所有行,否則僅返回符合條件的行。

    Psycopg將Python list改編爲Postgresql array。爲了檢查是否有任何PostgreSQL的array值等於某一值:

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

    要獲得一個Python None,其適於一個PostgreSQL null,從空的Python list

    parameter = [] or 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'儘管我也知道它的存在和所有......但是,這工作得很好,謝謝你的幫助! :) –

    相關問題