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

不羁岁月 提交于 2019-12-02 14:23:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!