如何使用可变数量的参数创建一个函数以生成SQL请求(python)?

时间:2013-12-30 23:28:51

标签: python sql parameters wildcard

我想创建一个包含SQL SELECT的“泛型”函数,但我希望这个函数能够接受一些未定义的参数。

我有这个代码:

def request(self, identifier= "%", sender="%", receiver="%", context="%", state="%"):
    result = None
    myConnection = MemoryManagement().getConnection()
    myCursor = myConnection.cursor()
    myCursor.execute("SELECT * from MemorySpace WHERE id = ? and sender = ? and receiver = ? and context = ? and state = ?", (identifier, sender, receiver, context, state))
    result = myCursor.fetchall()
    myCursor.close()
    myConnection.close()
    return result

问题是“%”不能作为通配符...我想知道是否有一个解决方案,我可以为这个问题编程自己? (即我不想使用框架或任何类型的层来访问sql数据库:))

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:))

还增加了一些可重用性

BASE_QUERY = '''
SELECT *
FROM MemorySpace
'''

def get_connection(self):
    return MemoryManagement().getConnection()

def get_result(self, query, args):
    cursor = self.get_connection()
    cursor.execute(query, args)
    result = cursor.fetchall()
    cursor.close()
    return result

def request(self, **kwargs):
    args = []
    filters = []

    for k, v in kwargs.iteritems():
        filters.append('%s = ?' % k)
        args.append(v)

    query = BASE_QUERY
    if filters:
        query += ' AND '.join(filters)

    return self.get_result(query, args)