登录
首页 >  数据库 >  MySQL

使用 NodeJS 删除 MySQL 表

来源:tutorialspoint

时间:2023-09-05 10:55:58 233浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《使用 NodeJS 删除 MySQL 表》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

您可以使用 Node.js 中的“DROP TABLE”语句从 MySql 数据库中删除现有表。有时,我们需要删除整个表,尽管在企业中总是建议将不使用的表归档而不是删除它们。

在删除表时,我们有两种情况 - p>

  • 如果表存在则删除,否则抛出错误

  • 无论表存在与否都删除。

我们将在这里讨论这两种情况。

在继续之前,请检查以下步骤是否已执行 -

  • mkdir mysql-test

  • cd mysql-test

  • npm init -y

  • npm install mysql

以上步骤是在项目文件夹中安装Node-mysql依赖。 p>

删除表

  • 删除表需要先创建app.js文件。

  • 现在将以下代码复制粘贴到 app.js 文件中

  • 使用以下命令运行代码

  • ul>
>> 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
}

好了,本文到此结束,带大家了解了《使用 NodeJS 删除 MySQL 表》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!

声明:本文转载于:tutorialspoint 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>