How to create a database in MySql with Node.js

August 30, 2022

Tags: Technologies

nodejs

 

A database is essential for any software project, be it a mobile application or a website, so developers use various technologies to create them there, among them MySQL. In this blog, we are going to learn how to use MySQL with Node.js framework.

 

 

nodejs

 

Creating a MySQL database with Node.js framework

 

We are going to explain how to create and use a MySQL database in Node.js, with the help of the Create Database query. This will be very useful for Node.js developers.

 

Syntax:

 

Create Database Query: CREATE DATABASE gfg_db;

Use Database Query: USE gfg_db

 

Modules: Node.js, ExpressJs, My SQL.

 

Create project

 

npm init

 

Install the modules

 

npm install express
npm install mysql

 

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 (error) {
      console.log("Database Connection Failed !!!", err);
    } else {
      console.log("connected to Database");
    }
});
  
module.exports = db_con;

 

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 ...`);
});

 

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`);
        })
    });
});

 

So we have created the mysql database using Node.js. You can use it for any of your projects.

 

On the Node.js official page they point out “As an event-driven asynchronous JavaScript runtime, Node.js is designed to create scalable network applications. In the following "hello world" example, many connections can be handled at the same time. On every connection, the callback is triggered, but if there is no work to do, Node.js will sleep.”

 

MySQL, on the other hand, is a database management system, as simple as that. It is a system that works to handle any type of information, from a simple shopping list to complex files of a large company.

 

We recommend you on video