3

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.

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.

1
  • what about doubling the %? e.g. cursor.execute("SELECT name FROM products WHERE rating > 3 AND category like 'Automation %%'"); Commented Oct 23, 2014 at 20:32

2 Answers 2

5

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. . .

Sign up to request clarification or add additional context in comments.

Comments

-3

Try to use format. If you have a string, against use %s you can use {}.

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. And, plus, you can get annoyed of % in your query.

1 Comment

This is also subject to sql injection . . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.