简体   繁体   English

无法在 Symfony 4 中使用 Doctrine2 DBAL\\Connection 插入数据

[英]Not able to INSERT data with Doctrine2 DBAL\Connection in Symfony 4

I am trying to insert some data in a MySQL table with Doctrine2 DBAL\\Connection ( for tables that I don't want to be mapped ), with this code:我正在尝试使用 Doctrine2 DBAL\\Connection(对于我不想映射的表)在 MySQL 表中插入一些数据,代码如下:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\DBAL\Connection;

class UtilsController extends AbstractController
{
    /**
     * @Route("/utils/fixer", name="utils_fixer")
     */
    public function dataFixer(Connection $conn)
    {
        $sql = "INSERT INTO test(id, username) VALUES (':id', ':name')";

        $id = 456;
        $name = 'blabla';

        $res = $conn->executeUpdate($sql, ['id' => $id, 'name' => $name]);

        return $this->render('utils/index.html.twig', ['res' => $res]);
    }
}

This is what my table looks like:这是我的表的样子:

在此处输入图片说明

This is giving me: "SQLSTATE[HY000]: General error: 1366 Incorrect integer value: ':id' for column 'id' at row 1".这给了我:“SQLSTATE[HY000]:一般错误:1366 不正确的整数值:第 1 行列 'id' 的 ':id'”。

The Id field has no auto increment , it's just a test table. Id 字段没有自动增量,它只是一个测试表。

SELECT statement is returning data OK. SELECT 语句返回数据正常。

Value binding doesn't seem to work ??值绑定似乎不起作用?

I used this Doctrine documentation .我使用了这个 Doctrine 文档

The placeholders shouldn't be quoted.不应引用占位符。

At least this gives a usage example of the executeUpdate() method.至少这给出了executeUpdate()方法的使用示例。

public function dataFixer(Connection $conn)
{
    $sql = "INSERT INTO test(id, username) VALUES (:id, :name)";

    $id = 456;
    $name = 'blabla';

    $res = $conn->executeUpdate($sql, ['id' => $id, 'name' => $name]);

    return $this->render('utils/index.html.twig', ['res' => $res]);
}

如果该值是自动递增的,则不应插入 $id 的值 - 正如我认为的那样。

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

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