使用 NodeJS 刪除 MySQL 表


您可以使用 Node 中的 "DROP TABLE" 語句從 MySql 資料庫中刪除現有表。有時,我們需要刪除整個表,儘管在企業中,建議將不再使用的表歸檔而不是刪除它們。

刪除表時,我們有兩種情況:

  • 如果表存在則刪除,否則丟擲錯誤

  • 無論表是否存在都刪除表。

我們將在這裡討論這兩種情況。

在繼續之前,請檢查以下步驟是否已執行:

  • mkdir mysql-test

  • cd mysql-test

  • npm init -y

  • npm install mysql

以上步驟用於在專案資料夾中安裝 Node - mysql 依賴項。

刪除表

  • 要刪除表,您需要首先建立一個 app.js 檔案。

  • 現在將以下程式碼複製貼上到 app.js 檔案中

  • 使用以下命令執行程式碼

>> node app.js

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

以上程式碼段將丟擲錯誤,因為我們沒有名為 customers 的表。我們有一個名為 students 的表。

輸出

Error: ER_BAD_TABLE_ERROR: Unknown table 'bo.customers'

示例 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;
   //Delete the "students" table:
   var sql = "DROP TABLE students";
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Table deleted");
      console.log(result);
   });
});

輸出

由於表存在,我們將得到以下輸出。

Table deleted
OkPacket {
   fieldCount: 0,
   affectedRows: 0,
   insertId: 0,
   serverStatus: 2,
   warningCount: 0,    // If table does exist, then the count = 0
   message: '',
   protocol41: true,
   changedRows: 0
}

如果存在則刪除表

那麼,我們如何克服上述情況呢?好吧,在上述情況下,我們可以使用 "If Exists" 子句。這隻會從資料庫中刪除一個表(如果它存在),否則它不會丟擲錯誤,而是會給出警告計數。

  • 將以下程式碼複製貼上到 app.js 檔案中

  • 使用以下命令執行程式碼

>> node app.js

示例

var mysql = require('mysql');
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   //Delete the "customers" table:
   var sql = "DROP TABLE IF EXISTS customers";
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Table deleted");
      console.log(result);
   });
});

輸出

Table deleted
OkPacket {
   fieldCount: 0,
   affectedRows: 0,
   insertId: 0,
   serverStatus: 2,
   warningCount: 1, // If table does not exist, then the count > 0
   message: '',
   protocol41: true,
   changedRows: 0
}

更新於:2021年4月27日

544 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.