Python MySQL 参数化查询与 LIKE 语句中的 % 通配符冲突

use*_*637 3 python mysql

我的执行查询失败:

cursor.execute("SELECT name FROM products WHERE rating > %s AND category like 'Automation %'", (3));
Run Code Online (Sandbox Code Playgroud)

因为它由于两个不同的原因而对百分比使用感到困惑——作为 LIKE 通配符和作为 python MySQL 数据库执行的参数。

如果我像这样运行这个查询,它会起作用:

cursor.execute("SELECT name FROM products WHERE rating > 3 AND category like 'Automation %'");
Run Code Online (Sandbox Code Playgroud)

如果我按如下方式运行查询,它会再次起作用:

cursor.execute("SELECT name FROM products WHERE rating > %s AND category = 'Automation '", (3));
Run Code Online (Sandbox Code Playgroud)

但这不是解决方案。我想同时使用通配符和参数。

我找到了一个解决方法,即将常量通配符作为变量传递:

 cursor.execute("SELECT name FROM products WHERE rating > %s AND category like %s", (3, 'Automation %'));
Run Code Online (Sandbox Code Playgroud)

这可行,但我需要一个更优雅的解决方案。我不想将常量作为变量传递。我的 SQL 语句在大型查询中可能有很多 LIKE 语句。

mgi*_*son 5

你也许可以使用额外的方法来逃避它%

cursor.execute("SELECT name FROM products WHERE rating > %s AND category like 'Automation %%'", (3));
Run Code Online (Sandbox Code Playgroud)

这显然适用于 MySQLdb,我希望它也适用于 python-mysql。。。