javascript - 使用node.js中的删除请求从数据库中动态删除数据
问题描述
我正在使用普通的 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();
}
});
推荐阅读
- django - django 有效地从 3 个模型中获取数据
- sql-server - 如何在 SSRS 中更新所有 Windows 文件共享交付的密码
- json - 加载多个 json 文件 - 'JSONDecodeError: Expecting value'
- html - 为什么此图像不在页面中心?
- powershell - Powershell 管道参数未传递给 Set-ADUser
- javascript - 将 curl 请求转换为获取 api watson
- android - 应用程序关闭后,服务未在 Android 中从 AlarmManager 启动
- r - ggplot2 在分面图后显示不准确的信息
- sql - SQL 查询:更新与另一列值匹配的列中的子字符串
- bash - Bash,将 grep 的结果相加