How to create MySQL database with node.js

To create MySQL database  with node.js we need first to create a connection to MySQL server then use the “CREATE DATABASE” statement. The following examples will show you exactly how to  create a database using the two types of connection: Single Connection and Connection Pool

Single connection

Single database connection means that you are using only one shared connection to execute all the queries triggered by all your application users. So, we use single connection only when the number of an application users at the same time is limited and theirs queries are simple.

To know more about single connection and how it works click here: What is Single Connection?.

//createDB.js

const connection = mysql.createConnection({
    password: “yourpassword”,
    host: localhost,
    user: “username”,
    port: 3306
  });


  connection.connect(function(err) {
    if (err) throw err;
    console.log("Connected to Mysql");
    connection.query("CREATE DATABASE ExampleDB", function (err, result) {
      if (err) throw err;
      console.log("ExampleDB database created");
    });
  });

Connection Pooling

Connection pools are used to improve the performance of the queries’s execution on a database without exception, prevent opening and closing connections frequently and reduce the number of new connections.

To know more about Connection Pooling and how it works click here: What is Connection Pooling and How it works?.

//createDB.js

const mysql = require('mysql');

const  pool = mysql.createPool({
    password: process.env.DB_PASS,
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    port: process.env.DB_PORT
  });


pool.query("CREATE DATABASE ExampleDB", function (err, result) {
    if (err) throw err;
    console.log("ExampleDB database created");
  })

Now run “createDB.js”

 node  createDB.js
Translate »