Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

NodeJS를 사용하여 MySQL 테이블 삭제

<시간/>

Node.js에서 "DROP TABLE" 문을 사용하여 MySql 데이터베이스에서 기존 테이블을 삭제할 수 있습니다. 때때로 우리는 전체 테이블을 삭제해야 하지만 기업에서는 항상 사용하지 않는 테이블을 삭제하는 대신 아카이브하는 것이 좋습니다.

테이블을 삭제하는 동안 두 가지 시나리오가 있습니다 -

  • 테이블이 있으면 삭제하고 그렇지 않으면 오류 발생

  • 존재 여부와 관계없이 테이블을 삭제합니다.

여기에서 두 시나리오에 대해 논의할 것입니다.

계속하기 전에 다음 단계가 이미 실행되었는지 확인하십시오 -

  • mkdir mysql-test

  • cd mysql-test

  • npm 초기화 -y

  • npm 설치 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);
   });
});

고객이라는 이름의 테이블이 없기 때문에 위의 스니펫은 오류를 발생시킵니다. 학생이라는 이름의 테이블이 있습니다.

출력

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
}