您可以使用 Node.js 中的“DROP TABLE”語句從 MySql 數(shù)據(jù)庫中刪除現(xiàn)有表。有時(shí),我們需要?jiǎng)h除整個(gè)表,盡管在企業(yè)中總是建議將不使用的表歸檔而不是刪除它們。
在刪除表時(shí),我們有兩種情況 – p>
如果表存在則刪除,否則拋出錯(cuò)誤
無論表存在與否都刪除。
我們將在這里討論這兩種情況。
在繼續(xù)之前,請檢查以下步驟是否已執(zhí)行 –
mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql
以上步驟是在項(xiàng)目文件夾中安裝Node-mysql依賴。 p>
刪除表
刪除表需要先創(chuàng)建app.js文件。
現(xiàn)在將以下代碼復(fù)制粘貼到 app.js 文件中
使用以下命令運(yùn)行代碼
ul>
>> node app.js
登錄后復(fù)制登錄后復(fù)制
示例 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); }); });
登錄后復(fù)制
上面的代碼片段將引發(fā)錯(cuò)誤,因?yàn)槲覀儧]有名為“customers”的表。我們有一個(gè)名為 – Students
輸出
的表
Error: ER_BAD_TABLE_ERROR: Unknown table 'bo.customers'
登錄后復(fù)制
示例 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); }); });
登錄后復(fù)制
輸出
由于表存在,我們將得到以下輸出。
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 }
登錄后復(fù)制
如果存在則刪除表
那么,我們?nèi)绾慰朔鲜銮闆r。好吧,在上面的例子中我們可以使用“If Exists”子句。這只會(huì)從數(shù)據(jù)庫中刪除表(如果存在),否則不會(huì)拋出錯(cuò)誤,但會(huì)給出警告計(jì)數(shù)。
復(fù)制粘貼以下內(nèi)容app.js 文件中的代碼
使用以下命令運(yùn)行代碼
>> node app.js
登錄后復(fù)制登錄后復(fù)制
示例
<!–
現(xiàn)場演示
–>
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); }); });
登錄后復(fù)制
輸出
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 }
登錄后復(fù)制
以上就是使用 NodeJS 刪除 MySQL 表的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!