1

I am new to python and currently learning to use SQL with python. I have the following code:

word = input("Enter a word: ")
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE '%s%' " % word)
results = cursor.fetchall()

The second line throws an error since I don't think I can use '%s%' like that? How would I change this so as to be able to make this work? I want to be able to return all related entries to the users input. So if the user inputs "rain", then I want the query to return all possible results e.g. "raining", "rainy" etc. Thank you.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
brian_dm
  • 13
  • 2

2 Answers2

1

You should use cursor.execute() parameter substitution rather than string formatting, to prevent SQL injection.

Then use CONCAT() to surround the search string with %.

query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE CONCAT('%', %s, '%' "), (word,))
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can try

query = cursor.execute(f"SELECT * FROM Dictionary WHERE Expression LIKE '%{word}%' ")
EnergyBoy
  • 547
  • 1
  • 5
  • 18