Bảng thả MySQL của Node.js


Xóa bảng

Bạn có thể xóa một bảng hiện có bằng cách sử dụng câu lệnh "DROP TABLE":

Thí dụ

Xóa bảng "khách hàng":

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

Lưu mã ở trên vào tệp có tên "demo_db_drop_table.js" và chạy tệp:

Chạy "demo_db_drop_table.js"

C:\Users\Your Name>node demo_db_drop_table.js

Điều này sẽ cung cấp cho bạn kết quả này:

Table deleted


Chỉ thả nếu tồn tại

Nếu bảng bạn muốn xóa đã bị xóa hoặc vì bất kỳ lý do nào khác không tồn tại, bạn có thể sử dụng từ khóa IF EXISTS để tránh gặp lỗi.

Thí dụ

Xóa bảng "khách hàng" nếu bảng tồn tại:

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 = "DROP TABLE IF EXISTS customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});

Lưu mã ở trên vào tệp có tên "demo_db_drop_table_if.js" và chạy tệp:

Chạy "demo_db_drop_table_if.js"

C:\Users\Your Name>node demo_db_drop_table_if.js

Nếu bảng tồn tại, đối tượng kết quả sẽ giống như sau:

{
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverstatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}

Nếu bảng không tồn tại, đối tượng kết quả sẽ giống như sau:

{
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverstatus: 2,
  warningCount: 1,
  message: '',
  protocol41: true,
  changedRows: 0
}

Như bạn có thể thấy, điểm khác biệt duy nhất là thuộc tính warningCount được đặt thành 1 nếu bảng không tồn tại.