参数化以sqlite中的查询开头

时间:2014-07-17 01:30:18

标签: python sqlite

我正在使用sqlite3的python绑定,我尝试进行类似的查询

表1

col1 | col2 
------------
aaaaa|1
aaabb|2
bbbbb|3

test.py

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()

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

预期行为:

>>> get_rows('aa')
[('aaaaa', 1), ('aaabb', 2)]

1 个答案:

答案 0 :(得分:4)

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

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

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