Bài viết hướng dẫn cập nhật bản ghi MySQL dùng NodeJS. Cập nhật động giá trị bảng MySQL từ Node.js server. Dùng SELECT sau update kiểm tra bản ghi đã cập nhật.
Trước khi bắt đầu, đảm bảo đã chạy:
mkdir mysql-testcd mysql-testnpm init -ynpm install mysql
(Các bước cài dependency Node-mysql trong thư mục dự án.)
Cập nhật bản ghi vào 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
// Kiểm tra dependency MySQL trong NPM
var mysql = require('mysql');
// Tạo kết nối mysql
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
});
Kết quả
1 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 1, // Số hàng cập nhật
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0', // Số hàng khớp
protocol41: true,
changedRows: 1
}
Ví dụ 2
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Cập nhật trường address kiểm tra address cũ
var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
});
Kết quả
3 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 3 Changed: 3 Warnings: 0',
protocol41: true,
changedRows: 3
}