Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

NodeJS MySQL Create Database

  • Difficulty Level : Medium
  • Last Updated : 09 Feb, 2021

Introduction:

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.

Syntax:

Create Database Query: CREATE DATABASE gfg_db;

Use Database Query: USE gfg_db

Modules:

  • 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.

    sqlConnection.js




    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:

    index.js




    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.

    Javascript




    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
Recommended Articles
Page :

Start Your Coding Journey Now!