Skip to content
Advertisement

Passing in Variables in Python to SQL Query

When I run the SQL query below I get the error print(db.execute(“SELECT * FROM (?);”), (tableName)) sqlite3.OperationalError: near “?”: syntax error

What is the correct way to pass in parameters to a SQL query?

Advertisement

Answer

You can’t dynamically bind object names in SQL, only values. For such a behavior, you’ll have to resort to string manipulation:

EDIT:
To address the concerns in the comment – yes, this technique is indeed more vulnerable to SQL Injection attacks. The common practice to protect against SQL Injection in such scenarios is to use a whitelist of allowed tables.

E.g.:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement