简体   繁体   English

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

[英]Python MySQL parameterized query conflicts with % wildcard in LIKE statement

My query on execution of this fails: 我的查询执行失败:

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

Because it gets confused about the percentage usage for two different reasons -- as a LIKE wildcard and as a parameter on python MySQL db execution. 因为它对百分比的使用感到困惑,原因有两个:作为LIKE通配符和作为Python MySQL db执行的参数。

If I run this query like this, it works: 如果我像这样运行此查询,它将起作用:

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

If I run the query as below, it again works: 如果我按以下方式运行查询,它将再次起作用:

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

But that's not a solution. 但这不是解决方案。 I want to use both the wildcard and the parameter. 我想同时使用通配符和参数。

I found a workaround, which is to pass in my constant wildcard as a variable: 我找到了一种解决方法,即将我的常量通配符作为变量传递:

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

This works but I need a more elegant solution. 这可行,但是我需要一个更优雅的解决方案。 I don't want to pass constants as variables. 我不想将常量作为变量传递。 My SQL statement could have a lot of LIKE statements in a big query. 我的SQL语句在一个大查询中可能有很多LIKE语句。

You can probably escape it using an extra % : 您可能可以使用额外的%转义:

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

This apparently works for MySQLdb and I would expect it to work for python-mysql as well. 这显然适用于MySQLdb ,我希望它也适用于python-mysql。 . .

Try to use format. 尝试使用格式。 If you have a string, against use %s you can use {}. 如果您有字符串,则可以不使用%s来使用{}。

sql = "SELECT name FROM products WHERE rating > {0} AND category like 'Automation %'"
slq = sql.format(3)
cursor.execute(sql);

This is much better and compliance to new versions of python. 这要好得多,并且符合新版本的python。 And, plus, you can get annoyed of % in your query. 另外,您可能会在查询中烦恼%。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM