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

StackOverflow https://stackoverflow.com/questions/10022040

Pregunta

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 ?)
¿Fue útil?

Solución

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

Otros consejos

You can't substitute metadata in parameterized queries.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top