NodeJS MySQL Create Database
Last Updated :
09 Feb, 2021
Improve
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
- Create Project
npm init
- Install Modules
npm install express npm install mysql
- 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;
- 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 ...`); });
- 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`); }) }); });
Output: Put this link in your browser http://localhost:5000/createDatabase
Created and Using gfg_db Database
Setting up environment and Execution: