Using the SQL LIKE operator with tuple insertion

PandaPanda :

I am trying to write a SQL query where a user inputs a name, and with tuple insertion the query returns similar names in the database using the LIKE operator.

This is what I tried:

user_input = input('Enter name: ')
c.execute('SELECT FirstName, LastName FROM Person WHERE FirstName LIKE('%' + ? + '%')', user_input)
user_input = input('Enter name: ')
c.execute('SELECT FirstName, LastName FROM Person WHERE FirstName LIKE '%' + user_input + '%'')
user_input = input('Enter name: ')
c.execute('SELECT FirstName, LastName FROM Person WHERE FirstName LIKE ?', '%' + user_input + '%')

However, the query fails to run and I am getting these errors.

TypeError: not all arguments converted during string formatting
TypeError: must be str, not tuple

Any help is appreciated!

blhsing :

You can either use double quotes to quote the SQL query in order to allow single quotes to quote the % characters:

c.execute("SELECT FirstName, LastName FROM Person WHERE FirstName LIKE '%' || ? || '%'",
    (user_input,))

or pass to the placeholder in the SQL query a string with user_input already enclosed in % characters:

c.execute('SELECT FirstName, LastName FROM Person WHERE FirstName LIKE ?',
    (f'%{user_input}%',))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=298119&siteId=1