Python和Psycopg2 |具有不同WHERE子句的动态查询

时间:2019-06-02 01:05:18

标签: python sql python-3.x postgresql psycopg2

我正在尝试创建一个函数,该函数根据传递给它的参数执行查询。

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table 
        WHERE filter1 = %s AND filter2 =%s AND filter3 = %s;'''
        cursor.fetchall()

但是只要任何一个过滤器都为None,那么我就不希望该参数成为SQL查询的一部分。

例如,如果仅使用过滤器1,那么我希望查询变为:

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table 
        WHERE filter1 = %s;'''
        cursor.fetchall()

如何做到这样才能动态生成查询?

1 个答案:

答案 0 :(得分:1)

COALESCE视为Python的None转换为SQL的NULL。下面的方法现在使用默认为None的可选args:

def sql_query(filter1=None, filter2=None, filter3=None):
    with ConnectionPool() as cursor:
        sql = '''SELECT * FROM table 
                 WHERE filter1 = COALESCE(%s, filter1) 
                   AND filter2 = COALESCE(%s, filter2) 
                   AND filter3 = COALESCE(%s, filter3);
              '''
        cursor.execute(sql, (filter1, filter2, filter3))
        cursor.fetchall()