MySQL in Node.js

What is Node.js

What is MySQL

Prerequisites

  1. You should have strong knowledge of Javascript.
  2. Basic knowledge of Node.js and Express.js.

Creating Express.js App using Node.js

npm init -y
npm install express mysql body-parser nodemon

Setting up Node.js App

const express = require("express");const app = express();const bodyParser = require("body-parser");app.use(bodyParser.json());app.get("/", (req, res)=>{console.log("Root route get request");res.send("This is root get request");});app.listen(5000, (req, res)=>{console.log("Server is listening on Port 5000")})

Setting up MYSQL

MySQL Workbench
XAMPP
{
host: "localhost",
user: "root",
password: "",
database: "testDB"
}
create database testDB
create table user
insert into user(username, password)
values("User1", "abc")
const express = require("express");const app = express();const bodyParser = require("body-parser");const { createPool } = require("mysql");app.use(bodyParser.json());// MySQL Database POOL connectionconst pool = createPool({host: "localhost",user: "root",password: "",database: "testDB",connectionLimit: 10});// end of pool connectionapp.listen(5000, (req, res)=>{console.log("Server is listening on Port 5000")})

Writing a Query

const express = require("express");const app = express();const bodyParser = require("body-parser");const { createPool } = require("mysql");app.use(bodyParser.json());// MySQL Database POOL connectionconst pool = createPool({host: "localhost",user: "root",password: "",database: "testDB",connectionLimit: 10});// end of pool connectionapp.get("/", (req, res)=>{console.log("Root route get request");pool.query("select * from user", (err, result, field)=>{if(err){console.log(err);}else{res.send(result);}});});app.listen(5000, (req, res)=>{console.log("Server is listening on Port 5000")})
const express = require("express");const app = express();const bodyParser = require("body-parser");const { createPool } = require("mysql");app.use(bodyParser.json());// MySQL Database POOL connectionconst pool = createPool({host: "localhost",user: "root",password: "",database: "testDB",connectionLimit: 10});// end of pool connectionapp.get("/", (req, res)=>{console.log("Root route get request");pool.query("selct * from user", (err, result, field)=>{if(err){console.log(err);}else{res.send(result);}});});app.listen(5000, (req, res)=>{console.log("Server is listening on Port 5000")})

--

--

Computer Science Graduate with MERN stack website development expertise.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.