node.js + mysql connection pooling

前端 未结 7 1113
执念已碎
执念已碎 2020-11-28 02:25

I\'m trying to figure out how to structure my application to use MySQL most efficent way. I\'m using node-mysql module. Other threads here suggested to use connection poolin

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 03:11

    When you are done with a connection, just call connection.release() and the connection will return to the pool, ready to be used again by someone else.

    var mysql = require('mysql');
    var pool  = mysql.createPool(...);
    
    pool.getConnection(function(err, connection) {
      // Use the connection
      connection.query('SELECT something FROM sometable', function (error, results, fields) {
        // And done with the connection.
        connection.release();
    
        // Handle error after the release.
        if (error) throw error;
    
        // Don't use the connection here, it has been returned to the pool.
      });
    });
    

    If you would like to close the connection and remove it from the pool, use connection.destroy() instead. The pool will create a new connection the next time one is needed.

    Source: https://github.com/mysqljs/mysql

提交回复
热议问题