database connection in node js code example

Example 1: how to manage a db connection in javascript

//put these lines in a seperate file
const mysql = require('mysql2');

const connection = mysql.createPool({
    host: "localhost",
    user: "",
    password: "",
    database: ""
    // here you can set connection limits and so on
});

module.exports = connection;

//put these on destination page
const connection = require('../util/connection');

async function getAll() {
    const sql = "SELECT * FROM tableName";
    const [rows] = await connection.promise().query(sql);
    return rows;
} 
exports.getAll = getAll;

Example 2: js read mysql database

// Use https://github.com/JackChilds/jsmysqldb

// Then once it's setup you can just do this:

// Config that will be sent to server
const config = {
  "table" : "customers",
  "limit" : "50",
  "offset" : "0"
};

// Use the _POST_REQUEST function to send data to the server and get a response
_POST_REQUEST("link-to-server/database.php", 'config=' + JSON.stringify(config), (response) => {
  // Convert the response into an array of rows:
  var data = JSON.parse(response);
  // Now do what you want with data
  // data[row index][column name]
});

Example 3: connect database backend in nodejs

const express = require('express');
const bodyParser = require('body-parser');
var connection  = require('express-myconnection'); 
var mysql = require('mysql');

const app = express(); 
app.use(bodyParser.json());

app.use(

        connection(mysql,{

            host: 'localhost', //'localhost',
            user: 'userEHX',
            password : 'hMmx56FN4GHpMXOl',
            port : 3306, //port mysql
            database:'sampledb'

        },'pool')); //or single

       app.post('/add_book',(req,res)=>{

        let {book_name,author,} = req.body;


        if(!book_name) return res.status(400).json('Book Name cant be blank');
        if(!author) return res.status(400).json('Author cant be blank');

        var data={book_name:book_name,
                  author:author};


         var query = connection.query("INSERT INTO books set ? ",data, 
        function(err, rows)
        {

          if (err){
            //If error
              res.status(400).json('Sorry!!Unable To Add'));
              console.log("Error inserting : %s ",err );
             }
         else
          //If success
          res.status(200).json('Book Added Successfully!!')

        });


        });


         app.listen(3000, ()=> {
      console.log(`app is running on port 3000`);
});