为什么“SQLSTATE [42000]:语法错误或访问冲突”?

时间:2013-10-02 21:23:25

标签: php mysql symfony doctrine-orm

我想运行这个Doctrine Query Builder查询:

$repository = $this->getDoctrine()->getRepository('MyBundle:Usage');
$usage_q = $repository->createQueryBuilder('u')->where('u.var = \'warranty\'');
$usage_result = $usage_q->getQuery()->getSingleResult();

但我总是得到:

  

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在第1行的'Usage u0_ WHERE u0_.var ='warranty''附近使用正确的语法

这是我的使用实体:

<?php

namespace Herbanist\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Usage
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Usage
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="var", type="string", length=20)
     */
    private $var;

    /**
     * @var string
     *
     * @ORM\Column(name="value", type="text")
     */
    private $value;


    public function getId()
    {
        return $this->id;
    }

    public function setVar($var)
    {
        $this->var = $var;

        return $this;
    }

    public function getVar()
    {
        return $this->var;
    }

    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    public function getValue()
    {
        return $this->value;
    }
}

使用表:

mysql> select * from `Usage`;
+----+----------+-------+
| id | var      | value |
+----+----------+-------+
|  1 | warranty | 0     |
+----+----------+-------+

2 个答案:

答案 0 :(得分:3)

这是因为'USAGE'是MySQL reserved word。所以我不得不将Usage表和Usage实体类重命名为其他类。

答案 1 :(得分:1)

使用反斜杠转义单引号只有在字符串在双引号内时才有效。

usage_q = $repository->createQueryBuilder('u')->where("u.var = 'warranty'");

最好不要利用参数。报价问题完全消失了。

usage_q = $repository->createQueryBuilder('u')->where('u.var = :something');
usage_q->setParameter('something','warranty');