简体   繁体   中英

Nodejs Mysql connection best practice

What is the best practice when we want to create MySql connection in nodejs.

  1. Create a global connection and use it for all queries
  2. Open a new connection for each query and close it after the query is done.

Connection pooling will handle your requests automatically.

This article covers the topic and might be helpful - https://medium.com/@mhagemann/create-a-mysql-database-middleware-with-node-js-8-and-async-await-6984a09d49f4

Define Global connection variable and use it in the whole project.



// only use when you have not setup app.set('con',con);
// global.con;

dbConnection = () => {

  // MYSQL database connection start
  let con = mysql.createPool('database Config obj here');

  // if you want use global.con variable
  // con = mysql.createPool(databaseConfig);

  con.getConnection((err) => {
    if (err) {
      //- The server close the connection.
      if (err.code === "PROTOCOL_CONNECTION_LOST") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Connection in closing
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Fatal error : connection variable must be recreated
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Error because a connection is already being established
      else if (err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Anything else
      else {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      setTimeout(dbConnection, 5000);
    } else {

      // you can also set the con varibale by calling below set method or else use global.con ;
      app.set('con', con);

      // rest of the code will goes here
    }
  });
}

dbConnection();


let con = app.get('con');
// => will have connection varibale here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM