我在Heroku上部署了一个NodeJS API,并尝试将其连接到MySQL数据库,因此我创建了一个connectionPool来处理ClearDB点火帐户(免费)上的连接,最多允许10个连接。
每次我对数据库执行查询时,它只会向堆栈添加一个新连接,直到它达到10个连接并且应用程序崩溃。
我的代码如下:
connectionFactory的:
var mysql = require('mysql');
function createDBConnection() {
var conn = mysql.createPool({
host: 'xxx',
user: 'xxx',
password: 'xxx',
database: 'xxx'
});
return conn;
}
module.exports = function() {
return createDBConnection;
}
这是我的选择查询:
function Dao(connection) {
this._connection = connection;
}
Dao.prototype.findAll = function (callback) {
this._connection.query('SELECT * FROM table',
function(errors, results) {
callback(errors,results);
});
};
module.exports = function() {
return Dao;
}
最后这是我用来称呼它的路线:
app.get('/products', function (req,res) {
var connection = app.persistence.connectionFactory();
var dao = new app.persistence.Dao(connection);
dao.findAll(function (err, result) {
res.format({
json: function () {
res.json(result);
}
});
});
});
我尝试将createPool()更改为createConnection(),然后在每次查询后立即调用.end()/。destroy()函数,但它根本不起作用。
任何提示?
答案 0 :(得分:0)
要关闭连接/返回与池的连接,请使用:connection.release()
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.
});
});