NodeJS MySQL Create Database (original) (raw)
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:
- 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;
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}`;
`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