针对使用Django的SQLite执行原始SQL会导致“ DatabaseError:靠近“?”:语法错误” [英] Executing raw SQL against SQLite with Django results in `DatabaseError: near "?": syntax error`

查看:92
本文介绍了针对使用Django的SQLite执行原始SQL会导致“ DatabaseError:靠近“?”:语法错误”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当我使用 cursor.execute() 已记录

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

不使用Django的参数替换时,查询将按预期工作:

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?

注意:


  • 为查询添加后缀; 没有帮助

  • 根据文档,%s 应该而不是SQLite的(Django将%s 转换为

  • Suffixing the query with ; does not help
  • As per the documentation, %s should be used, not SQLite's ? (Django translates %s to ?)

推荐答案

您不能在SQL语句中使用参数代替标识符(列或表名)。您只能使用它们代替单个

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.

相反,您必须使用动态SQL来构造整个SQL字符串并将其发送,未参数化的数据库)(如果表名源自代码之外,请格外小心以避免注入)。

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

这篇关于针对使用Django的SQLite执行原始SQL会导致“ DatabaseError:靠近“?”:语法错误”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆