MySQL Connection with NodeJS/ExpressJS

Make sure you have setup a basic express application.

First create a Mysql Workbench Table

open mysql workbench, follow these steps:

  • Create a New Schema
  • Create a Table
  • Create Fields (fields, datatype, nn, pk, ai) (nn-not null, ai-auto increase)
  • Right click the table and select all rows
  • Fill the data

Install MYSQL2

npm install mysql2

Create the Connection

const mysql=require('mysql')

const db = mysql.createConnection({

  host: 'localhost',

  user: 'myuser',

  password: 'mypassword',

  database: 'mydatabase'

})

Make a GET Request (fetch data)

app.get("/api/product", (req, res)=>{

    const q = "SELECT * FROM product"

    db.query(q, (err, data)=>{

    if(err) res.json(err)

    return res.json(data)

    })

 })

— Download Postman

First download the Postman App, its very helpful for REST API.

Now open the localhost url and send a GET request.

Now it’s time for sending a POST request.

Send a POST Request (Create a New Data)

app.post('/product', (req, res) => {
  const query = `
    INSERT INTO product 
    (product_name, small_des, big_des) 
    VALUES (?)
  `;

  const values = ['pineapple', 'mango', 'watermelon'];

  db.query(query, [values], (err, data) => {
    if (err) return res.json(err);
    return res.json(data);
  });
});