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

db = sqlite3.Connection(":memory:")
db.execute("CREATE TABLE Students(name);")
tableName = "Students"
var1 = "Jon"
var2 = "Steve"
var3 = "Chuckie"
db.execute("INSERT INTO Students VALUES (?), (?), (?)", (var1, var2, var3))
print(db.execute("SELECT * FROM (?);"), (tableName))

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:

queryTemplate = 'SELECT * FROM %s'
tableName = 'Students'
query = queryTemplate % tableName

print(query)

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.:

allowedTables = ['students', 'teachers']
if tableName not in allowedTables:
    raise ValueError('Wrong table')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement