[英]How to Insert records on sql db using node js?
I have a post route on my node.js server and I want to send a json object on the body request to insert that on a sql database.我的 node.js 服务器上有一个 post 路由,我想在 body 请求中发送一个 json 对象以将其插入到 sql 数据库中。
If I use "INSERT INTO users(UserInfo, BitMask) Values ("value1", 1)"
it works, but If I try to scape the object like on the example below it doesn't.如果我使用
"INSERT INTO users(UserInfo, BitMask) Values ("value1", 1)"
它可以工作,但是如果我尝试像下面的示例那样对对象进行转义,则它不会。
I also tried "INSERT INTO users(UserInfo, BitMask) Values ?", [client],
But it doesnt work.我也试过
"INSERT INTO users(UserInfo, BitMask) Values ?", [client],
但它不起作用。
router.post("/add/client", (request, res) => {
let client = {}
client.UserInfo = request.body.name;
client.BitMask = request.body.bitmask;
pool.request().query("INSERT INTO users(UserInfo, BitMask) Values ?" + mysql.escape(client),
(err, result)=>{
if(!err){
return res.json({ success: true, data: result, records_added: result.affected_rows });
}
return res.json({ success: false, data: err });
})
});
This code returns the following object:此代码返回以下对象:
{
"success": false,
"data": {
"code": "EREQUEST",
"number": 0,
"originalError": {
"sqlstate": "07002",
"code": 0
},
"name": "RequestError"
}
}
Anyone knows what I am missing here?有人知道我在这里缺少什么吗? One of the answers I have found on google was that The problem comes from using a placeholder multiple times in a query, but it doesn't seem to be the case.
我在 google 上找到的答案之一是问题来自在查询中多次使用占位符,但似乎并非如此。
Thanks for the help.谢谢您的帮助。
Use a parameterized query, I'd also opt for async
/ await
syntax for better readability使用参数化查询,我也会选择
async
/ await
语法以获得更好的可读性
router.post("/add/client", async (request, res) => {
try {
const result = await pool.request()
.input('userInfo', request.body.name)
.input('bitmask', request.body.bitmask)
.query("INSERT INTO users(UserInfo, BitMask) Values (@userInfo, @bitmask)");
return res.json({
success: true,
data: result, // I would avoid this, potential to leak DB info to the client
records_added: result.affected_rows
});
} catch (e) {
// consider returning next(e) here and handling errors somewhere common
return res.json({
success: false,
data: err // don't do this, again potential to leak DB info to the client
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.