📜  NodeJs MySQL 删除表

📅  最后修改于: 2022-05-13 01:56:57.174000             🧑  作者: Mango

NodeJs MySQL 删除表

DROP TABLE Query 用于从 MySQL 数据库中删除或删除表。

句法:

  • 这将删除用户表。但是如果用户表不存在,这将引发错误。
    DROP TABLE users
  • 这将仅在存在时删除用户表。
    DROP TABLE IF EXISTS users

      模块:

      • mysql:处理 MySQL 连接和查询
        npm install mysql

      SQL gfg_db
      数据库预览(显示表格):



      示例 1:删除用户表

      Javascript
      const mysql = require("mysql");
        
      let db_con  = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: '',
          database: 'gfg_db'
      });
        
      db_con.connect((err) => {
          if (err) {
            console.log("Database Connection Failed !!!", err);
            return;
          }
        
          console.log("We are connected to gfg_db database");
        
          // here is our query
          let query = 'DROP TABLE users';
        
          db_con.query(query, (err, rows) => {
              if(err) throw err;
        
              console.log('Deleted users Table');
          });
      });


      Javascript
      const mysql = require("mysql");
        
      let db_con  = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: '',
          database: 'gfg_db'
      });
        
      db_con.connect((err) => {
          if (err) {
            console.log("Database Connection Failed !!!", err);
            return;
          }
        
          console.log("We are connected to gfg_db database");
        
          // notice the if exists in below query
          let query = 'DROP TABLE IF EXISTS users';
        
          db_con.query(query, (err, rows) => {
              if(err) throw err;
        
              console.log('Deleted users Table');
          });
      });


      输出:

      示例 2:仅当存在时才删除 users 表

      Javascript

      const mysql = require("mysql");
        
      let db_con  = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: '',
          database: 'gfg_db'
      });
        
      db_con.connect((err) => {
          if (err) {
            console.log("Database Connection Failed !!!", err);
            return;
          }
        
          console.log("We are connected to gfg_db database");
        
          // notice the if exists in below query
          let query = 'DROP TABLE IF EXISTS users';
        
          db_con.query(query, (err, rows) => {
              if(err) throw err;
        
              console.log('Deleted users Table');
          });
      });
      

      输出: