在MySQL + Python中使用AND运算符参数化子字符串查询的安全方法

时间:2014-07-11 14:59:38

标签: python mysql

我试图从给定的字符串安全地构建SQL查询。该字符串可以包含空格。

string = "chair"

query = """SELECT *
             FROM albums
             WHERE title LIKE %s"""
values = ('%' + string + '%',)
cur.execute(query,values)
# >> SELECT * FROM albums WHERE title LIKE '%chair%'

但我无法弄清楚如何安全地扩展它以使用AND运算符搜索多个单词。

string = "big blue chair"
# >> SELECT * FROM albums WHERE title LIKE '%big%' AND
#                               title LIKE '%blue%' AND
#                               title LIKE '%chair%'

(我知道这是FULLTEXT搜索的内容等等......但这是一个非常小的数据集,并且足够快。)

2 个答案:

答案 0 :(得分:3)

如果您想根据query动态展开valuesstring,可以这样做:

string = "big blue chair"
query = "SELECT * FROM albums WHERE title LIKE %s"
values = ["%{}%".format(val) for val in string.split()]
for _ in values[1:]:  # iterate over len(values) - 1
    query += " AND title LIKE %s"
print(query)
print(values)

输出:

SELECT * FROM albums WHERE title LIKE %s AND title LIKE %s AND title LIKE %s
['%big%', '%blue%', '%chair%']

答案 1 :(得分:0)

将字符串拆分为空格。

然后:

cursor.execute("SELECT * FROM albums WHERE title LIKE %s AND title LIKE %s AND title LIKE %s", (var1 , var2, var3))