ในบทความนี้ เราจะมาดูกันว่าเราจะอัปเดตบันทึกใน MySQL โดยใช้ NodeJS ได้อย่างไร เราจะอัปเดตค่าตาราง MySQL แบบไดนามิกจากเซิร์ฟเวอร์ Node.js คุณสามารถใช้คำสั่ง select หลังจากอัปเดตเพื่อตรวจสอบว่าบันทึก MySql ได้รับการอัพเดตหรือไม่
ก่อนดำเนินการ โปรดตรวจสอบว่าได้ดำเนินการตามขั้นตอนต่อไปนี้แล้ว -
-
mkdir mysql-test
-
cd mysql-test
-
npm init -y
-
npm ติดตั้ง mysql
ขั้นตอนข้างต้นใช้สำหรับการติดตั้ง Node - mysql dependecy ในโฟลเดอร์โปรเจ็กต์
การอัปบันทึกลงในตารางนักเรียน -
-
สำหรับการอัปเดตระเบียนที่มีอยู่ในตาราง MySQL ให้สร้างไฟล์ app.js ก่อน
-
ตอนนี้คัดลอกและวางตัวอย่างด้านล่างในไฟล์
-
รันโค้ดโดยใช้คำสั่งต่อไปนี้
>> node app.js
ตัวอย่าง
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
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);
});
}); ผลลัพธ์
1 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 1, // This will return the number of rows updated.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the
number of rows matched.
protocol41: true,
changedRows: 1 } ตัวอย่าง
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Updating the fields with address while checking the address
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);
});
}); ผลลัพธ์
3 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 3, // This will return the number of rows updated.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched.
protocol41: true,
changedRows: 3 }