我使用正常的http请求使用node.js从mysql数据库中删除值。但是现在,只有动态地删除静态值。我想通过提供id动态删除数据。
const server = http.createServer();
const reqUrl = url.parse(req.url, true);
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let sql = "Delete from students where id=12";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});
现在,在运行此代码localhost:3000/delete之后,只会删除id = 12。但我想这样做localhost:3000/delete?id=12给输入值作为id。
我尝试将sql命令作为“从id =?的学生中删除” ,但它给出了错误。我怎么解决这个问题?
这应该很简单。
您只需要从您的请求中接收参数并将其附加到字符串。
这是您更新的代码。
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let studid = req.query.id; //Get the student id
let sql = "Delete from students where id="+studid; //append it to query
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});