问题
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?
)
回答1:
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).
回答2:
You can't substitute metadata in parameterized queries.
来源:https://stackoverflow.com/questions/10022040/executing-raw-sql-against-sqlite-with-django-results-in-databaseerror-near