如何为多个查询创建一个接受零个、一个或多个占位符的函数?

问题描述 投票:0回答:1

因为我对不同的表有多个查询,并且具有不同的占位符,所以我想为此创建一个函数。但我无法决定这个函数的参数

例如

def function_q(query, placeholder):
    cursor.execute(query, (placeholder,))
    return cursor.fetchall()

但是如果我需要在没有占位符或超过 1 个占位符的情况下调用此函数,第二个参数应该是

list
*args 
?两者我都会出错。 函数调用将像这样并且有效:

person_id = 100
result = function_q('SELECT name FROM persons WHERE n_id = ?;', person_id)

但是如果我有多个占位符,这意味着函数调用将类似于:

person_id = 100
age = 30
result = function_q('SELECT name FROM persons WHERE n_id = ? and age = ?;', person_id, person_age)
python sqlite
1个回答
1
投票

placeholder
变量
cursor.execute(query, (placeholder,))
中删除元组并假设它是一个可迭代对象。

import sqlite3
db_path = ':memory:'


def function_q(query, placeholders):
    cur.execute(query, placeholders) # renamed cursor variable!
    return cur.fetchall()


# multiple placeholders
q1 = 'SELECT * FROM sample_table WHERE col1=? and col2=?;'
phs1 = ('x', 'y')

# single placeholders
q2 = 'SELECT * FROM sample_table WHERE col2=?;'
phs2 = ('yy',)

# no placeholders
q3 = 'SELECT * FROM sample_table;'
phs3 = tuple()


test = [(q1, phs1), (q2, phs2), (q3, phs3)]

# create and populate db
statement = """
CREATE TABLE sample_table (col1, col2);
INSERT INTO sample_table (col1, col2) VALUES ('x','y');
INSERT INTO sample_table (col1, col2) VALUES ('xx','yy');
"""
with sqlite3.connect(db_path) as con:
    # db initialisation
    cur = con.cursor()
    cur.executescript(statement)

    # run the test with different placeholders
    for q, phs in test:
        res = function_q(q, phs)
        print(*res)

    # execution multiple placeholders query
    q = 'SELECT * FROM sample_table WHERE col1=? and col2=?;'
    print(function_q(q, ('xx', 'yy'))) # notice the iterable object

#('x', 'y')
#('xx', 'yy')
#('x', 'y') ('xx', 'yy')
#[('xx', 'yy')]
© www.soinside.com 2019 - 2024. All rights reserved.