Executing raw SQL against SQLite with Django results in `DatabaseError: near "?": syntax error`

Go To StackoverFlow.com

1

For example, when I use cursor.execute() as documented:

>>> from django.db import connection
>>> cur = connection.cursor()
>>> cur.execute("DROP TABLE %s", ["my_table"])
django.db.utils.DatabaseError: near "?": syntax error

When Django's argument substitution is not used, the query works as expected:

>>> cur.execute("DROP TABLE my_table")
django.db.utils.DatabaseError: no such table: my_table

What am I doing wrong? How can I make parameterized queries work?

Notes:

  • Suffixing the query with ; does not help
  • As per the documentation, %s should be used, not SQLite's ? (Django translates %s to ?)
2012-04-05 02:49
by David Wolever


6

You cannot use parameters in SQL statements in place of identifiers (column or table names). You can only use them in place of single values.

Instead, you must use dynamic SQL to construct the entire SQL string and send that, unparameterized, to the database (being extra careful to avoid injection if the table name originates outside your code).

2012-04-05 02:52
by Larry Lustig


3

You can't substitute metadata in parameterized queries.

2012-04-05 02:51
by Ignacio Vazquez-Abrams
Ads