简体   繁体   English

Django:将参数传递给原始SQL查询时出现MySQL语法错误

[英]Django: MySQL syntax error when passing parameters to raw SQL query

I'm trying to perform a raw SQL query, like so 我正在尝试执行原始SQL查询,就像这样

test = Poll.objects.raw('SELECT * FROM %s', ['polls_poll'])

and it results in an error: 它会导致错误:

ProgrammingError at ...

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax...

Debug Toolbar shows that Django performs the following SQL query: 调试工具栏显示Django执行以下SQL查询:

SELECT * FROM 'polls_poll'

If I execute this query directly in the MySQL shell, it won't work either, unless I replace single quotes (') with backticks (`). 如果我直接在MySQL shell中执行此查询,它也不会工作,除非我用反引号(`)替换单引号(')。

How do I make Django use backticks? 如何让Django使用反引号? Or what am I doing wrong? 或者我做错了什么?

Environment: Django 1.6, MySQL 5.6.14, OS X 10.9. 环境:Django 1.6,MySQL 5.6.14,OS X 10.9。

I think you can only pass query parameters , not field names , so it will not work for table names. 我认为您只能传递查询参数 ,而不能传递字段名称 ,因此它不适用于表名。

Alternatively, you can try simple string building for your query: 或者,您可以尝试为查询构建简单的字符串:

test_query = 'SELECT * FROM %s' % 'polls_poll'
test = Poll.objects.raw(test_query)

Although, string formatting for raw queries is not recommended. 但是,不建议使用原始查询的字符串格式。

More information: https://docs.djangoproject.com/en/dev/topics/db/sql/#passing-parameters-into-raw 更多信息: https//docs.djangoproject.com/en/dev/topics/db/sql/#passing-parameters-into-raw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM