首页 > 解决方案 > mySql 插入语法 - 不插入预期的内容

问题描述

我有这个 INSERT 查询。它确实在表中创建了一条记录,但“client”值为 0,“short”值为 null。但是,所有控制台日志都显示正确的数据。我假设这是我使用问号时的简单语法错误。但我找不到它,或者似乎也只能使用变量名让它工作。任何帮助表示赞赏。

app.put("/audit/create", function (req, res) {
  console.log("It is getting to the route");
  const client = req.body.client;
  const short = req.body.short;
  console.log(`client: ${client}`);
  console.log(`short: ${short}`);
  connection.getConnection(function (err, connection) {
      connection.query(
        `INSERT INTO audits (client, short)
        VALUES (?, ?)`,
        [
          {
            client: client,
          },
          {
            short: short,
          },
        ],
        function (error, results, fields) {
          if (error) throw error;
          res.json(results);
          console.log(`Audit has been created`);
        }
      );
    connection.release();
  });
});

我还尝试使用 ${client}、${short} 的变量名称代替问号......这仍然给了我相同的结果。但是,呈现 ${client} 和 ${short} 的控制台日志确实记录了我期望看到的正确数据。

标签: javascriptmysqlput

解决方案


为什么将对象作为值传递给查询?试试:

connection.query(
    'INSERT INTO audits (client, short) VALUES (?, ?)',
    [ client, short ],
    function ...

推荐阅读