Node Js connection with SQL Database

 Step 1: Initialize Node js Backend

 npm init

Step 2 : Installing express and MySQL package

npm i express mysql nodemon

express - node js framework to make our life easy

mysql - MySQL package which enables us to connect with SQL database

nodemon - server auto-restart on save


"MAKE SURE TO ADD NODEMON TO package.json file"

package.json file 

{
  "name": "node-with-sql",
  "version": "1.0.0",
  "description": "leaning connection bewtween node and sql",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"nodemon ./index.js" //make sure to add this
  },
  "author": "Himanshu Shekhar",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mysql": "^2.18.1"
  }
}

> It should look somewhat like this

Now run the application : 

npm start

Step 3 : 

>Start your xampp and create - 

Database - 'sampleDB'

Table - 'logindata'


>Add some data into logindata table

Now that database is ready, let's connect with the backend

 

Step 4: Code for connection with backend

index.js file :

const express = require("express");
const mysql = require("mysql");
const app = express();

const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "sampleDB",
});

connection.connect(function (error) {
  if (error) {
    console.log("error");
  } else {
    console.log("connected with database ", connection.config.database);
    console.log("connected on port", connection.config.port);
    console.log("connected with hostname", connection.config.host);
  }
});

app.get("/", function (req, res) {
  connection.query("select * from logindata", function (err, result, fields) {
    if (err) {
      console.log("error in query", err);
    } else {
      res.json({
        "logidata table data ": result,
      });
      console.log("data fetch from database", result);
    }
  });
});

app.listen(4000);

now run - npm start

Go to browser and type : http://localhost:4000/



And its connected!!!!!!







0 Comments