Computer >> Máy Tính >  >> Lập trình >> MySQL

Cập nhật bản ghi trong MySQL bằng NodeJS

Trong bài viết này, chúng ta sẽ xem cách chúng ta có thể cập nhật một bản ghi trong MySQL bằng NodeJS. Chúng tôi sẽ cập nhật động các giá trị bảng MySQL từ máy chủ Node.js. Bạn có thể sử dụng câu lệnh select sau khi cập nhật để kiểm tra xem bản ghi MySql có được cập nhật hay không.

Trước khi tiếp tục, vui lòng kiểm tra các bước sau đã được thực hiện chưa -

  • mkdir mysql-test

  • cd mysql-test

  • npm init -y

  • npm cài đặt mysql

Các bước trên là để cài đặt Node - mysql dependecy trong thư mục dự án.

Cập nhật Bản ghi vào Bảng Sinh viên -

  • Để cập nhật bản ghi hiện có vào bảng MySQL, trước tiên hãy tạo tệp app.js

  • Bây giờ sao chép-dán đoạn mã dưới đây vào tệp

  • Chạy mã bằng lệnh sau

>> node app.js

Ví dụ

// 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);
   });
});

Đầu ra

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 }

Ví dụ

// 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);
   });
});

Đầu ra

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 }