I looked all over for the answer to my question and could not find any good answer.... I am using python with the sqlite3 module to query a database. The problem is that I cannot get a sql query to hold multiple variables. For example...
I can get this query to work perfectly. ("wordsofar" is the variable name)
c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)
However I cannot get this code to work. ("wordsofar" and "noletter" are the variable names)
c.execute("SELECT word FROM wordlist WHERE word LIKE ? AND word NOT LIKE ?", (wordsofar, noletter))
It gives me the error: "Error binding parameter 0"
I have tried to rewrite the query so instead of "?" it is using the named convention such as shown by http://docs.python.org/py3k/library/sqlite3.html (about half way down the page) but that did not solve the problem.
Any help would be much appreciated. Thank-you!
2 Answers 2
This line (that you say works) shows that wordsofar is a sequence of one element:
c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)
In this case the second line should be:
c.execute("SELECT word FROM wordlist WHERE word LIKE ? AND word NOT LIKE ?",
wordsofar + (noletter,))
If noletter is a string and wordsofar is a tuple (as you say in your comment).
execute() docs say that the second argument is always parameters. If you use '?' then number of parameters (len(parameters)) is equal to number of '?' in the sql statement.
1 Comment
You code looks fine.
The problem is in the data. Either wordsofar or noletter is an object that sqlite3 doesn't know how to store.
One solution is to pickle the object. Another solution is to supply converter and adapter functions.
Use register_adapter to register a callable to convert the custom Python type type into one of SQLite’s supported types.
The docs also describe how to supply converters to handle the reverse conversion:
SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If you want to use other types you must add support for them yourself. The detect_types parameter and the using custom converters registered with the module-level register_converter() function allow you to easily do that.
Here's a related SO question with answers.
4 Comments
__a__ and noletter look like %b% The problem is solved and it works correctly by making the query look like what @J.F. Sebastian recommended.wordsofar with wordssofar[0] to extract the underlying string.