Node.js mySQL 发布数据时出现语法错误
Node.js mySQL syntax error when posting data
我是 Node.js 和一般服务器的新手,刚开始尝试在我的服务器中实施数据库。我有 mySQL 数据库和 table 设置,服务器连接到数据库并且服务器开始处理 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();
});
试试这个:
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
});
我是 Node.js 和一般服务器的新手,刚开始尝试在我的服务器中实施数据库。我有 mySQL 数据库和 table 设置,服务器连接到数据库并且服务器开始处理 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();
});
试试这个:
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
});