Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Xóa bảng MySQL dùng NodeJS

Xóa bảng hiện có từ MySQL Database dùng câu lệnh DROP TABLE trong Node. Đôi khi cần xóa toàn bộ bảng, tuy nhiên trong doanh nghiệp luôn khuyên archive bảng không dùng thay vì xóa.

Khi xóa bảng, có 2 tình huống:

  • Xóa bảng nếu tồn tại, ngược lại báo lỗi
  • Xóa bảng có tồn tại hay không

Thảo luận cả hai.

Trước khi bắt đầu, đảm bảo đã chạy:

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

Xóa bảng

  • Tạo file app.js
  • Copy code dưới vào app.js
  • Chạy: node app.js

Ví dụ 1

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ảng "customers":
  var sql = "DROP TABLE customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table deleted");
    console.log(result);
  });
});

Đoạn trên báo lỗi vì không có bảng customers. Ta có bảng students.

Kết quả

Error: ER_BAD_TABLE_ERROR: Unknown table 'bo.customers'

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;
  // Xóa bảng "students":
  var sql = "DROP TABLE students";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table deleted");
    console.log(result);
  });
});

Kết quả

Bảng tồn tại, nhận kết quả:

Table deleted
OkPacket {
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,  // Nếu bảng tồn tại, count = 0
  message: '',
  protocol41: true,
  changedRows: 0
}

Xóa bảng nếu tồn tại (IF EXISTS)

Khắc phục tình huống trên dùng mệnh đề IF EXISTS. Chỉ xóa bảng nếu tồn tại, không báo lỗi, chỉ trả warning count.

  • Copy code vào app.js
  • Chạy: node app.js

Ví dụ

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ảng "customers" nếu tồn tại:
  var sql = "DROP TABLE IF EXISTS customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table deleted");
    console.log(result);
  });
});

Kết quả

Table deleted
OkPacket {
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverStatus: 2,
  warningCount: 1,  // Nếu bảng KHÔNG tồn tại, count > 0
  message: '',
  protocol41: true,
  changedRows: 0
}