0

I have a nodejs app that connects to mysql When I leave connection open the server close it and when I use con.destroy or con.end I cant reconnect to mysql.

What should I do and is it better to keep closing and opining new connection for each request knowing there will be a lot.

module.exports = class DataAccessLayer {
constructor() {
    this.con = mysql.createConnection({
        host: ("host.com"),
        user: ("asdfg"),
        password: ("zxcvb"),
        database: ("DB_example")
    });

    this.con.connect(function (err) {
        if (err) throw err;
        console.log("Connected to DB");
    });
}

getUserBySenderId(senderId) {
    this.con.query("SELECT sender_id,first_name,last_name,creation_date " +
        "FROM USER " +
        "WHERE sender_id = '" + senderId + "'",
        function (err, result, fields) {
            if (err) throw err;
            console.log(result);
        });
}

4 Answers 4

4

For your problem, you can visit this document https://www.npmjs.com/package/mysql#pooling-connections.

Instead of every time making a query and again and again doing database hit to MYSQL. Also need to remember when to close connection and when to open is a quite cumbersome task. You can use Sequelize http://docs.sequelizejs.com/ (ORM). This will help you from all these pains and let you focus on your business logic instead of having technical errors.

HTH Thanks!

Sign up to request clarification or add additional context in comments.

Comments

2

Creating and tearing down a database connection on every request will degrade the response time of each request thereby impacting overall performance. You should consider using connection pool as documented at https://www.npmjs.com/package/mysql#pooling-connections. The connection pool will insulate the application from scenarios such as the server terminating an idle connection due to lack of activity.

Comments

0
    "use strict"
    const mysql = require("mysql");

    class DB {
      constructor() {
        this.conn = mysql.createConnection({
          host: 'localhost',enter code here
          user: 'root',
          password: 'pass',
          database: 'db_name'
        });
      }

      connect() {
        this.conn.connect(function (err) {
          if (err) {
            console.error("error connecting: " + err.stack);
            return;
          }
          console.log("connected to DBB");
        });
      }

      checkQuery(id) { 

        try {
          this.conn.query(`SELECT * FROM tablename WHERE id = ${id}`, function (err, result) {
            if (err) {
              console.log('err');
              throw err;
            } else {
              console.log(result);

            }
          });
        } catch (e) {
          console.log('Exception caught in checkQuery()', e)
        }
      }

module.exports = DB
var obj = new DB();
obj.checkQuery(2);

Comments

0

You should use mysql pooling, nonetheless if you want to open and close a connection for every request, you can use async

const async = require('async')
const mysql = require('mysql')

const db = mysql.createConnection(DBInfo)
const query = 'SOME MYSQL QUERY'

async.series([
  function (next) {
    db.connect(function (err) {
      if (err) {
        console.error('error connecting: ' + err.stack)
        next(Error(err))
      } else {
        console.log('Connection successfuly')
        next()
      }
    })
  },
  function (next) {
    db.query(query, function (err, results, fields) {
      if (err) {
        next(Error(err))
      } else {
        console.log(query + ' submitted with success')
        next()
      }
    })
  },
  function (next) {
    db.end(function (err) {
      if (err) {
        next(Error(err))
      } else {
        next()
      }
    })
  }
],
function (err, results) {
  if (err) {
    console.error('There was an error: ', err)
    db2.end()
  }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.