Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

อัปเดต Record ใน MySQL ด้วย Node.js

อัปเดต Record ใน MySQL ด้วย Node.js Dynamic Update

Prerequisites

mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql

อัปเดต Record ในตาราง Students

  1. สร้าง app.js
  2. Copy Code ด้านล่าง
  3. Run: node app.js

ตัวอย่างที่ 1: Update โดย WHERE Name

var mysql = require('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);
  });
});

Output

1 Record(s) updated.
OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '(Rows matched: 1 Changed: 1 Warnings: 0',
  protocol41: true,
  changedRows: 1
}

ตัวอย่างที่ 2: Update โดย WHERE Address

var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';";

Output

3 Record(s) updated.
OkPacket {
  affectedRows: 3,
  message: '(Rows matched: 3 Changed: 3 Warnings: 0',
  changedRows: 3
}

แนะนำ: ใช้ SELECT หลัง Update เพื่อยืนยัน