发布数据时,Node.js mySQL语法错误

时间:2018-03-31 18:11:16

标签: mysql node.js node-mysql

我一般都是Node.js和服务器的新手,刚刚开始尝试在我的服务器中实现数据库。我有mySQL数据库和表设置服务器连接到数据库和服务器开始处理SQL查询,但由于我的INSERT中的语法错误它打破了查询,我一直在看论坛并且在没有运气的情况下更改了我的代码几次...如果你能看到我出错的地方,请帮忙!谢谢!

router.post('/', (req, res, next) => {
    console.log(req.name);
    const imageJSON = {
        //attributes of item that server will request (more important for db
        name: req.body.name,
        image: req.body.image
    };
    //console.log(req.body.image);

    res.status(201).json({
        message: imageJSON
    });
    connection.connect(function(err){
        if(!err) {
            console.log("Database is connected ... nn");
        } else {
            console.log("Error connecting database ... nn");
        }
    });
    var post = {id: 1, name: req.body.name, image: req.body.image};
    connection.query('INSERT INTO "images" ("id", "name", "image") VALUES ?', post,
        function(err, rows, fields) {
            connection.end();
            if (!err)
                console.log('The solution is: ', rows);
            else
                console.log('Error while performing Query.', err);
        });
    //connection.end();
});

1 个答案:

答案 0 :(得分:1)

试试这个:

var post = {id: 1, name: req.body.name, image: req.body.image};
var query = connection.query('INSERT INTO images SET ?', post, function 
   (error, rows, fields) {
      // ... operation on result
});