คุณสามารถลบตารางที่มีอยู่ออกจากฐานข้อมูล MySql โดยใช้คำสั่ง "DROP TABLE" ใน Node.js บางครั้ง เราจำเป็นต้องลบทั้งตาราง แม้ว่าในองค์กร ขอแนะนำให้เก็บถาวรตารางที่ไม่ได้ใช้แทนการลบทิ้ง
ขณะลบตาราง เรามีสองสถานการณ์ -
-
การลบตารางหากมีอยู่ มิฉะนั้นจะเกิดข้อผิดพลาด
-
การลบตารางไม่ว่าจะมีอยู่หรือไม่
เราจะหารือเกี่ยวกับสถานการณ์ทั้งสองที่นี่
ก่อนดำเนินการ โปรดตรวจสอบว่าได้ดำเนินการตามขั้นตอนต่อไปนี้แล้ว -
-
mkdir mysql-test
-
cd mysql-test
-
npm init -y
-
npm ติดตั้ง mysql
ขั้นตอนข้างต้นใช้สำหรับการติดตั้ง Node - mysql dependecy ในโฟลเดอร์โปรเจ็กต์
การลบตาราง
-
หากต้องการลบตาราง คุณต้องสร้างไฟล์ 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);
});
}); ตัวอย่างข้างต้นจะเกิดข้อผิดพลาดเนื่องจากเราไม่มีตารางที่มีชื่อลูกค้า เรามีโต๊ะชื่อ - นักเรียน
ผลลัพธ์
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
} การลบตารางหากมีอยู่
แล้วเราจะเอาชนะสถานการณ์ข้างต้นได้อย่างไร ในกรณีข้างต้น เราสามารถใช้ประโยค "ถ้ามี" ได้ การดำเนินการนี้จะลบตารางออกจากฐานข้อมูลหากมีอยู่เท่านั้น มิฉะนั้นจะไม่เกิดข้อผิดพลาด แต่จะนับการเตือน
-
คัดลอกและวางโค้ดต่อไปนี้ในไฟล์ 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
}