3

I am currently using Python 2.7's SQLite 3 database API. When I go to execute a query like such:

c.execute('''select ? from music where ? like "%?%"''', (attr, attr, query))

I get the following error:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 3 supplied.

I think that the %?% is what's throwing it off.

1 Answer 1

3

You misunderstand the use of parameter substitution. You can use ? in place a whole, single variable value in the SQL statement. You cannot use it in place of column or table names, nor can you use it as part of a larger string value.

In this case you could do this:

c.execute('SELECT colname FROM music WHERE other_colname LIKE ?', ('%' + query + '%'))

If you want to sub in the column names you must do it using string formatting. If you do so and the values came from user input, you need to be careful to avoid SQL injection. You're protected for the substituted parameters, but not the string formatting.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. It's a bummer to not be able to substitute the database entity names, but the engine would not be able to prepare and pre-compile the query without that information available.

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.