Skip to content
Related Articles
Open in App
Not now

Related Articles

NodeJS MySQL Create Database

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 09 Feb, 2021
Improve Article
Save Article


We are going to see how to create and use mysql database in nodejs. We are going to do this with the help of CREATE DATABASE query.


Create Database Query: CREATE DATABASE gfg_db;

Use Database Query: USE gfg_db


  • NodeJs
  • ExpressJs
  • MySql

    Setting up environment and Execution:

  1. Create Project
    npm init
  2. Install Modules
    npm install express
    npm install mysql
  3. Create and export mysql connection object.


    const mysql = require("mysql");
    let db_con  = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: ''
    db_con.connect((err) => {
        if (err) {
          console.log("Database Connection Failed !!!", err);
        } else {
          console.log("connected to Database");
    module.exports = db_con;

  4. Create Server:


    const express = require("express");
    const database = require('./sqlConnection');
    const app = express();
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);

  5. Create Route to Create Database and use it.


    app.get("/createDatabase", (req, res) => {
        let databaseName = "gfg_db";
        let createQuery = `CREATE DATABASE ${databaseName}`;
        // use the query to create a Database.
        database.query(createQuery, (err) => {
            if(err) throw err;
            console.log("Database Created Successfully !");
            let useQuery = `USE ${databaseName}`;
            database.query(useQuery, (error) => {
                if(error) throw error;
                console.log("Using Database");
                return res.send(
    `Created and Using ${databaseName} Database`);

  6. Output: Put this link in your browser http://localhost:5000/createDatabase

    Created and Using gfg_db Database

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!