【问题标题】:INSERT INTO query not working in Express.jsINSERT INTO 查询在 Express.js 中不起作用
【发布时间】:2016-10-19 15:33:18
【问题描述】:

我在将数据插入 MySQL 数据库时遇到问题。选择查询工作正常,所以我假设这是我错过的一些愚蠢的东西,无论是在 Express 代码中,还是在我的 HTML 中。我从中运行查询的页面位于localhost:8080/add,我正在尝试INSERT INTO。这是我的代码:

Javascript

app.get('/add', function(req, res) {
    res.sendFile(path.join(__dirname + '/Views/add.htm'));
});

app.post('/add', function(req, res) {
    var fName = req.body.fName;
    var email = req.body.email;
    var id = req.body.id;
    var post = {id: id, user: fName, email: email};
    console.log(post);//This holds the correct data

    connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
        if (!err) {
            console.log('Successfully added information.');
        } else {
            console.log('Was not able to add information to database.');
        }
    });
});

我的 HTML 只是一个提交按钮和 3 个输入字段,位于 POST 方法表单中。同样,我可以连接到数据库并使用选择查询从中读取数据,但我无法插入其中。

【问题讨论】:

  • VALUES (?) 需要圆括号,如果您插入 3 列,我会想到 VALUES (?,?,?)
  • 但如果您使用参数替换,可能还需要准备
  • @RiggsFolly 我刚刚编辑了我的问题以进一步解释我的问题,希望它会有所帮助。

标签: javascript mysql node.js express


【解决方案1】:

查看此处的文档https://github.com/mysqljs/mysql#escaping-query-values

connection.query('INSERT INTO posts SET ?', post, function(err, result) {
        if (!err) {
            console.log('Successfully added information.');
        } else {
            console.log(result);
            console.log('Was not able to add information to database.');
        }
});

有效的mysql语句是SET而不是Values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多