Signup/Sign In

Create MySQL Database using NodeJS

This guide will show you how to make a MySql database (schema) using a NodeJS program. You can bind to a database with NodeJS and perform tasks such as generating a table, selecting data from tables, updating rows in tables, inserting data into tables, and deleting data from a database.

A database in NodeJS is implemented as a directory that includes all files that belong to the database's tables. To initiate a new database in NodeJS, the syntax for the CREATE DATABASE declaration is as follows:

CREATE DATABASE [IF NOT EXISTS] database_name
[CHARACTER SET charset_name]
[COLLATE collation_name]

You must first install Node in order for this to be feasible. js is the correct kit.

Using the NodeJS package to create a new database

Before initiating the process I'll highly recommend you to look at and implement the previous article i.e. connecting Mysql with NodeJS so that you can understand things better without any dificulty. With that said, we set the following parameters, which makes it easier to bind to the database.

  1. Host: This parameter specifies the server that operates the database.
  2. User: Sets the user’s name
  3. Password: Sets up a password
  4. Database: Gives the database a name.

Look at the following snippet for more clarity. Here's some NodeJS code to build a MySQL database (schema):

console.log("Application starts ...");
var mysql = require('mysql');
 
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234",
  database: "world"
});
 
var databaseName = "myDatabase";
 
con.connect(function(err) {
  console.log("[create database in MySql] - block BEGIN ");  
  if (err) throw err;
  varId = 6;
  con.query("create database "+databaseName, function (err, result, fields) {
    if (err) throw err;
   // console.log(result);
  });
  con.end();
   
  console.log("[create database in MySql] - block END");
 
});
 
console.log("END of the application.");

Output:

output

Conclusion

Finally, congratulations you're one step closer to becoming a master in MySQL, you discovered how to build a new database using the NodeJS CREATE DATABASE statement in the MySQL curriculum and the CREATE SCHEMA statement in NodeJS.



About the author: