sqlite中的参数化startswith查询

Ant*_*ile 0 python sqlite

我正在为 sqlite3 使用 python 绑定,我正在尝试执行这样的查询

表格1

col1 | col2 
------------
aaaaa|1
aaabb|2
bbbbb|3
Run Code Online (Sandbox Code Playgroud)

测试文件

def get_rows(db, ugc):
    # I want a startswith query.  but want to protect against potential sql injection
    # with the user-generated-content
    return db.execute(
        # Does not work :)
        "SELECT * FROM table1 WHERE col1 LIKE ? + '%'",
        [ugc],
    ).fetchall()
Run Code Online (Sandbox Code Playgroud)

有没有办法安全地做到这一点?

预期行为:

>>> get_rows('aa')
[('aaaaa', 1), ('aaabb', 2)]
Run Code Online (Sandbox Code Playgroud)

CL.*_*CL. 5

在 SQL 中,+用于添加数字。您的 SQL 最终为... WHERE col1 LIKE 0.

要连接字符串,请使用||

db.execute(
    "SELECT * FROM table1 WHERE col1 LIKE ? || '%'",
    [ugc],
)
Run Code Online (Sandbox Code Playgroud)