0

I am creating an API app with SQlite3 in Python. It all works fine until I process an item with ' in the name column. The entry will get written to the DB but the code will break when I try getting that item from the database with this:

received_data = {"name": "Example with ' name", "price": 43,...}
new_item = cursor.execute("SELECT * FROM items WHERE name='{}'".format(received_data['name'])).fetchall()

I get this error:

new_item = cursor.execute("SELECT * FROM items WHERE name='{}'".format(received_data['name'])).fetchall()
sqlite3.OperationalError: near "name": syntax error

What is the best solution to this since I can't guess (I guess...) all the characters that someone might use in the name?

JLeno46
  • 1,186
  • 2
  • 14
  • 29

1 Answers1

0

Don't use format for this at all, it is dangerous. Use a parameterized query:

new_item = cursor.execute("SELECT * FROM items WHERE name=?", (received_data['name'],)).fetchall()
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25