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:
Setting up environment and Execution:
npm init
npm install express npm install mysql
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;
const express = require("express");
const database = require('./sqlConnection');
const app = express();
app.listen(5000, () => {
console.log(`Server is up and running on 5000 ...`);
});
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4