插入自定义mysql数据库表

时间:2019-05-14 04:10:04

标签: mysql node.js ajax

我目前正在尝试将数据插入保存到变量的特定表名中,但是每次尝试执行操作时,我都会不断收到ER_PARSE_ERROR。

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Test' SET `date` = '201
9-05-07', `league` = '1', `matchup` = '1'' at line 1

这是我发帖请求的样子

app.post('/addData', function(req, res) {
  var id = req.body.id
  var data = {
    date: req.body.date,
    league: req.body.league,
    matchup: req.body.matchup,
  }
  con.query('INSERT INTO ? SET ?', [id, data], function(err, resp) {
    if (err) throw err;
    res.redirect('back');
  });
});

从错误消息看来,传递到查询中的Test周围还有其他引号,但是在进行console.log(id)时,它只是打印出不带引号的Test。

2 个答案:

答案 0 :(得分:0)

app.post('/addData', function (req, res) {

    var data = {
        id: req.body.id,
        date: req.body.date,
        league: req.body.league,
        matchup: req.body.matchup,
    };
    con.query('INSERT INTO Test SET ?', data, function (err, resp) {
        if (err) throw err;
        res.redirect('back');
    });
});

您可以试试吗?

答案 1 :(得分:0)

// This is the best ES6 way you can try out make some changes in your date format.
app.post('/addData', async (req, res) => {

    var data = {
        id: req.body.id,
        date: req.body.date,
        league: req.body.league,
        matchup: req.body.matchup,
    };
    await con.query('INSERT INTO Test SET ?', data, (err, resp) => {
        if (err) throw err;
        res.redirect('back');
    });
});