Node.js MySQL查询错误ER_PARSE_ERROR

时间:2016-05-04 15:04:47

标签: mysql node.js

我在NodeJS应用程序中遇到MySQL查询问题。在我的代码片段中,我循环遍历三重嵌套for循环并在 post 变量中保存一些不同的数据。我想要做的是检查这些数据是否已经存在于数据库中,如果没有,则执行 INSERT 查询。

一直在尝试,但是我收到以下错误:

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 ' `user_id` = '421', `product_id` = '1', `brick_id` = '1', `effect_date` = '2016-' at line 1

我认为没有任何SQL错误,我已经检查了一千次,但也许我错过了一些东西。这就是我试图做的事情:

router.post('/relations/finalize', function (req, res, next) {
    // Executing a cycle for every possible data combination
    for (var i = 0; i < req.body.users_selection.length; i++) {
        for (var j = 0; j < req.body.products_selection.length; j++) {
            for (var k = 0; k < req.body.bricks_selection.length; k++) {
                post = {
                    owner_id: req.session.userid,
                    user_id: req.body.users_selection[i],
                    product_id: req.body.products_selection[j],
                    brick_id: req.body.bricks_selection[k],
                    effect_date: req.body.year + "-" + req.body.month + "-01 00:00:00",
                }

                // Checking if the entry already exists
                req.app.locals.connection.query({
                    sql: 'SELECT * FROM relations WHERE user_id = ? AND product_id = ? AND brick_id = ? AND effect_date >= ?',
                    timeout: 40000, // 40s
                    values: [post]
                }, function (err, rows, fields) {
                    if (err) throw err;
                    else {
                        if (rows.length > 0) {
                            console.log("The entry already esists");
                        } else {
                            req.app.locals.connection.query("INSERT INTO relations SET ?", post, function (err, row, fields) {
                                if (err) throw err;
                                else {
                                    console.log("The entry didn't exists and was then created.");
                                    //res.redirect("/relations/wizard");
                                }
                            });
                        }
                    }
                });
            }
        }
    }
});

任何帮助都将非常感谢您解决此问题。

编辑:我还尝试将单独的值传递给SELECT查询,如下所示:

values: req.body.users_selection[i], req.body.products_selection[j], req.body.bricks_selection[k], req.body.year + "-" + req.body.month + "-01 00:00:00"

但我得到的结果是INSERT查询被调用X次,具有相同的值,因为for循环没有经过,可能是因为Node的异步性质。

0 个答案:

没有答案