Sau khi insert, cũng cần xóa bản ghi. Bản ghi xóa dựa trên định danh từ bảng database. Dùng câu lệnh DELETE FROM.
Có 2 cách xóa bản ghi từ MySQL DB:
- Xóa tĩnh (Static Deletion) – Cho giá trị lọc cố định trước để xóa.
- Xóa động (Dynamic Deletion) – Yêu cầu input trước khi xóa, xóa dựa trên input đó.
Trước khi bắt đầu, đảm bảo đã chạy:
mkdir mysql-testcd mysql-testnpm init -ynpm install mysql
Ví dụ xóa bản ghi từ MySQL dùng Nodejs:
Xóa bản ghi từ bảng Students
- Tạo file
app.js - Copy đoạn code dưới vào file
- Chạy:
node app.js
Ví dụ 1 (Xóa tĩnh)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Xóa bản ghi address="Delhi"
var sql = "DELETE FROM student WHERE address = 'Delhi';";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Record deleted = ", result.affectedRows);
console.log(result);
});
});
Kết quả
Record deleted = 1
OkPacket {
fieldCount: 0,
affectedRows: 1, // Số bản ghi xóa
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
Ví dụ 2 (Xóa động)
Ví dụ sau nhận trường address làm input, chỉ xóa bản ghi khớp bộ lọc.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Xóa bản ghi mong muốn từ bảng
let sql = `DELETE FROM student WHERE address = ?`;
// xóa hàng address=Delhi
con.query(sql, 'Delhi', (err, result, fields) => {
if (err) throw err;
console.log("Record deleted = ", result.affectedRows);
console.log(result);
});
});
Kết quả
OkPacket {
fieldCount: 0,
affectedRows: 3, // 3 hàng xóa cho address=Delhi
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}