Example drop table in mysql with nodejs

Delete a Table

You can delete an existing table by using the "DROP TABLE" statement:

Example: Delete the table "customers"

 

var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "",

  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);

  });

});

 

Run and result:

 

C:\Nodejs>node mysqlDropTable.js

Table deleted

OkPacket {

  fieldCount: 0,

  affectedRows: 0,

  insertId: 0,

  serverStatus: 2,

  warningCount: 0,

  message: '',

  protocol41: true,

  changedRows: 0 }

 

Drop Only if Exist

If the the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error.

Example: Delete the table "customers" if it exists

 

var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "",

  database: "mydb"

});

con.connect(function(err) {

  if (err) throw err;

  /*Delete the "customers" table, but only if it already exist (to avoid errors):*/

  var sql = "DROP TABLE IF EXISTS customers";

  con.query(sql, function (err, result) {

    if (err) throw err;

    console.log(result);

  });

});

 

Run :

- If the table exist:

 

C:\Nodejs>node mysqlDropTableIfExist.js

OkPacket {

  fieldCount: 0,

  affectedRows: 0,

  insertId: 0,

  serverStatus: 2,

  warningCount: 0,

  message: '',

  protocol41: true,

  changedRows: 0 }

 

- If the table does not exist:

 

C:\Nodejs>node mysqlDropTableIfExist.js

OkPacket {

  fieldCount: 0,

  affectedRows: 0,

  insertId: 0,

  serverStatus: 2,

  warningCount: 1,

  message: '',

  protocol41: true,

  changedRows: 0 }