Django:将参数传递给原始SQL查询时的MySQL语法错误 [英] Django: MySQL syntax error when passing parameters to raw SQL query

查看:207
本文介绍了Django:将参数传递给原始SQL查询时的MySQL语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一个原始的SQL查询,像这样

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

它会导致错误: $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $手册对应于您的MySQL服务器版本正确的语法...

调试工具栏显示Django执行以下SQL查询:

  SELECT * FROM'polls_poll'

如果我直接在MySQL shell中执行这个查询,它也不会工作,除非我用反引号(`)替换单引号(')。



如何使Django使用反引号?或者我做错了什么?



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

解决方案

我想你只能传递查询参数,而不是字段n ames ,所以它不适用于表名。



或者,您可以尝试简单的字符串构建您的查询:

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

虽然不建议使用原始查询的字符串格式。



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


I'm trying to perform a raw SQL query, like so

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:

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

How do I make Django use backticks? Or what am I doing wrong?

Environment: 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

这篇关于Django:将参数传递给原始SQL查询时的MySQL语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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