SQLite中的参数化startswith查询
我正在使用Python的sqlite3库,想要进行一个类似这样的查询
表格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 个回答
8
在SQL中,+
用来加数字。
你的SQL语句变成了... WHERE col1 LIKE 0
。
如果你想把字符串连接在一起,可以用||
:
db.execute(
"SELECT * FROM table1 WHERE col1 LIKE ? || '%'",
[ugc],
)