简体   繁体   English

Nodejs Mysql 连接最佳实践

[英]Nodejs Mysql connection best practice

What is the best practice when we want to create MySql connection in nodejs.当我们想在 nodejs 中创建 MySql 连接时,最佳实践是什么。

  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本文涵盖了该主题,可能会有所帮助 - 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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