假设我想在数据库中进行字符串前缀搜索,比如说
select * from some_table where name like 'abcde%';
其中abcde
实际上是一些用户输入字符串。我如何在Python中的MySQLdb中做到这一点?我可以想到两种方式:
cursor.execute("""select * from some_table where name like '%s%%'""", (some_prefix_to_search))
OR
cursor.execute("""select * from some_table where name like %s""", (some_prefix_to_search + '%'))
哪一个是正确的方法?对于方法1,MySQLdb是否正确地指出'%s %%'是一个整体,因此它将生成'abcde%'而不是''abcde'%',即将%s替换为字符串值或者没有引号?
对于方法2,输入字符串中的%是否会被视为某个特殊值并被转义?
感谢。
答案 0 :(得分:1)
你的第一种方法不起作用; mysqldb将再次引用您的输入值,查询将引发语法错误。
您的第二种方法有效,因为execute
方法只需要在查询模板字符串中考虑%
一个特殊字符,以便它可以识别占位符并决定插入参数的位置。它没有理由在参数值本身中考虑%
一个特殊字符,因为%
不是可用于SQL注入的字符。