0

I'm trying to pass my variable into a statement with 'LIKE' but I'm getting all kinds of formatting errors. I tried cursor.execute("SELECT title FROM movies WHERE title LIKE '%%s%'" %Keyword) and other variants of it, but nothing works. How can I get the LIKE statement to interprit my variable?

Im using MySQL workbench and the 'Keyword' variable stores input from a FORM tag in html. The whole project is based on making a search website.

4
  • What version of python are you using ? Commented May 4, 2021 at 10:00
  • It will help people answer if you can provide some sample code that shows the modules and code that you're writing, as well as describe the backend SQL system that is accepting the statement. There are nuances between systems and so tagging your question appropriately and providing sample code will help us find someone who can answer you more confidently. Commented May 4, 2021 at 10:52
  • @FlorianCastelain Python 3.9 Commented May 4, 2021 at 15:27
  • @Josh Theres not that much to add as the code is really short, but I'm saving user input in a variable, and thats the variable I'm trying to pass into the SQL statement. Commented May 4, 2021 at 15:31

2 Answers 2

1

According to the docs, you should not use this way of formatting your strings:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

Example with .format:

query = "SELECT title FROM movies WHERE title LIKE '%{s}%'".format(s=Keyword)

cursor.execute(query)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use format :

 cursor.execute("SELECT title FROM movies WHERE title LIKE '%{}%'".format(Keyword))

Comments

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.