3
#!/usr/bin/python
import sqlite3

conn = sqlite3.connect("/home/michael/Dropbox/lagniappe/database.db")

cursor = conn.cursor()

query = raw_input('Search for a title:')

cursor.execute("SELECT * FROM nerd WHERE title LIKE '%?%';", query)

print cursor.fetchall()

Retuns the error:

michael@piplup:~$ python sqlite.py 
Search for a title:test
Traceback (most recent call last):
  File "sqlite.py", line 10, in <module>
    cursor.execute("SELECT * FROM nerd WHERE title LIKE '%?%';", query)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 4 supplied.

All I want it to do is to print out the data it receives from the database to the console. Eventually I would like to manipulate this data, but I just need the query to work right.

3 Answers 3

2

There are two problems here. First, the parameter is supposed to be a sequence - Python is interpreting it as a list of four characters, rather than a four-character string.

Secondly, the placeholder has to be the entire element, and not in quotes. You'll need to add the percent characters yourself:

query = raw_input('Search for a title:')
query = '%' + query + '%'
cursor.execute("SELECT * FROM nerd WHERE title LIKE ?", (query,))
Sign up to request clarification or add additional context in comments.

Comments

0

First, the second parameter of the execute method is supposed to be a sequence, and you are passing a string (which is interpreted as a sequence of characters), that's why it says ... and there are 4 supplied.

Second, the quotes around the argument of your LIKE comparison prevent the execute method to interpret the ? as a placeholder; instead it's being interpreted as the literal ?.

So, for your query to work correctly, you have to do two things:

  1. Add the % to your the query argument, insted of embedd them into the SQL query.
  2. Pass the query argument inside a sequence (a one-element tuple or list).

Here's how your script would look like:

#!/usr/bin/python
import sqlite3
conn = sqlite3.connect("/home/michael/Dropbox/lagniappe/database.db")
cursor = conn.cursor()
query = '%%%s%%' % raw_input('Search for a title:') # puts the input between %
cursor.execute("SELECT * FROM nerd WHERE title LIKE ?;", (query,)) # passes the query as a tuple
print cursor.fetchall()

Comments

0

You need to pass a tuple to cursor.execute. Try (query,) instead of query.

cursor.execute("SELECT * FROM nerd WHERE title LIKE '%?%';", (query,))

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.