Skip to content
Advertisement

Searching for a keyword, inputted by the user using sqlite3 and python 3.7

I want to search for a post using the keyword inputted from the user in python 3.7, I came up with two solutions but none worked, here’s what I did.

Possible solution 1:

c.execute("SELECT pid FROM posts WHERE title LIKE '%?%';", (keyWord,))

However, it gives me this error

Exception has occurred: ProgrammingError
Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.

Possible solution 2:

keyWord = "'%" + keyWord + "%'"
c.execute("SELECT pid FROM posts WHERE title LIKE ?;", (keyWord,))

This time returns an empty list, I tried hardcoding a value using the normal method:

c.execute("SELECT pid FROM posts WHERE title LIKE '%a%';")

and it did return the desired values, so the code should output a result.

Advertisement

Answer

Try:

c.execute("SELECT pid FROM posts WHERE title LIKE ?", ('%'+keyWord+'%',))

In your case, you can also use instr which return the index of the substring you’re searching for (0 otherwise):

c.execute("SELECT pid FROM posts WHERE instr(title, ?) > 0", (keyWord,))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement