逃脱字符串%

时间:2016-07-28 11:52:58

标签: python mysql pymysql

我使用PyMySQL从python中的MySQL数据库进行查询:

filter = "Pe"
connection = pymysql.connect(host="X", user="X", password="X", db="X", port=3306, cursorclass=pymysql.cursors.SSCursor)
cursor = connection.cursor()
sqlquery = "SELECT * FROM usertable WHERE name LIKE '%%s%'"
cursor.execute(sql, (filter))
response = cursor.fetchall()
connection.close()

这不会返回任何内容。 我可以写:

sqlquery = "SELECT * FROM usertable WHERE name LIKE '%" + filter +"%'"

并执行:cursor.execute(sql),但后来我失去了转义,这使得程序容易受到注入攻击,对吗?

我可以在不丢失转义的情况下将值插入LIKE吗?

...WHERE name LIKE '%%%s%%'"不起作用。我认为%s在被替换的转义字符串的两侧添加'作为其在PyMySQL中的函数的一部分。

2 个答案:

答案 0 :(得分:1)

您需要将整个模式作为查询参数传递,并使用 元组

filter = "%Pe%"
sql = "SELECT * FROM usertable WHERE name LIKE %s"
cursor.execute(sql, (filter,))

答案 1 :(得分:0)

将要保留的%加倍。

sqlquery = "SELECT * FROM usertable WHERE name LIKE '%%%s%%'"
相关问题