如何在nodejs中自动closuresmysql连接

目前我的进程挂起,因为mysql池没有被自动closures。

我假定当我调用connection.release() ,如果没有其他人使用连接,连接就会closures。 但似乎并非如此。 我的代码如下所示:

getConnection.js:

 var mysql = require('mysql'); var pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : 'mysql', database : 'xxx' }); module.exports = function getConnection(callback){ pool.getConnection(function(err, connection){ if (err) { throw err; } callback(connection); }); } 

我正在使用它:

 var getConn = require('./getConnection'); function selectOne(query, map, cb){ getConn(function(conn){ conn.query(query, map, function(err, rows){ if (err) { throw err; } cb(rows.length ? rows[0] : false); conn.release(); }); }); } 

我想我错过了一些东西。 当我释放它时不应该node-mysqlclosures连接?

https://github.com/felixge/node-mysql#pooling-connections conn.release(); 允许连接释放到连接池,因此不会closures连接。 如果要closures连接,请使用conn.end(); 根据文档: https : //github.com/felixge/node-mysql#terminating-connections 。

我采取了和Ishaan类似的方法,但是我认为我的理解有点清晰。

这是我的代码片段。

 // Dependencies var mysql = require('mysql'), config = require("../config"); /* * @sqlConnection * Creates the connection, makes the query and close it to avoid concurrency conflicts. */ var sqlConnection = function sqlConnection(sql, values, next) { // It means that the values hasnt been passed if (arguments.length === 2) { next = values; values = null; } var connection = mysql.createConnection(config.db); connection.connect(function(err) { if (err !== null) { console.log("[MYSQL] Error connecting to mysql:" + err+'\n'); } }); connection.query(sql, values, function(err) { connection.end(); // close the connection if (err) { throw err; } // Execute the callback next.apply(this, arguments); }); } module.exports = sqlConnection; 

比你可以在任何地方使用它只是做像

 var mysql_query = require('../models/mysql_query'); mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows) { console.log(rows); }); 

希望这可以帮助。

如果我错了,我在这里很新,所以原谅我。

这是我如何做到这一点

 module.exports = { getDBConnection: function () { return mysql.createConnection(config.db); }, connectToDB: function (connection) { connection.connect(function (err) { if (err) { throw err; } }); }, endDBConnection: function (connection) { connection.end(function (err) { if (err) { throw err; } }); }, exec: function (query, data, cb) { var connection = this.getDBConnection(); this.connectToDB(connection); connection.query(query, data, function(err, res) { if (err) { cb(err); } cb(null, res); }); this.endDBConnection(connection); } } 

这是configurationvariables

  db: { host: 'localhost', user: 'root', password: '', database: 'test' },