Sunday, April 26, 2020

Node.js Mysql creating a new database

Node.js Mysql

Creating A New Database

We can create a new database using the "CREATE DATABASE MYDATABASE_NAME" query.

    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "root", //username
      password: "secret"  //your secret password

    con.connect(function(err) {
      if (err) throw err;
      console.log("Connected to the database successfully");
       //creating a database with name "empdb"
      con.query("CREATE DATABASE empdb", function (err, result) {
        if (err) throw err;
        console.log("Database created successfully");

Save the file createdb.js and run using the command,

C:\Users\user\Desktop\brackets>node test.js

The result will be,

 Connected to the database successfully
 Database created successfully


We can verify if the database is created or not, (see the screenshot below)

  • Open a command prompt window and reach the MySQL installation directory bin folder using CD command. 
  • Run mysql -p command and provide the password.
  • To verify if the database is created or not, use the SHOW DATABASES command.