mysql连接无法释放,Promise-MySQL无法将连接释放回池

本文讨论了一位新手在使用Node.js进行MySQL数据库查询时遇到的问题。使用promise-mysql库创建了连接池,但在尝试释放连接回池时出现错误:`conn.release is not a function`。解决方案是调用`pool.releaseConnection(conn)`来正确释放连接。这确保了连接池的有效管理和资源的合理利用。
摘要由CSDN通过智能技术生成

I am very new to Node.js development and I am working on an app that requires me to pull users from a mysql database. I am using the promise-mysql library to query a mysql database. I am trying to use a connection pool like this:

var pool = mysql.createPool({

host: hgh.host,

user: hgh.user,

password: hgh.pw,

database: hgh.name,

connectionLimit: 10

});

As a global variable in my module.

I then have the above function to return a connection from the pool.

function connect() {

return pool.getConnection().then(function(connection) {

return connection

}).catch(function(error) {

console.log("Connect failed");

throw ErrorModel.generateErrorObject(error, 500);

});

}

Below is a function I am using to query the database with:

function getUser(username) {

var sql_query = `SELECT * FROM userstable WHERE userName = ` + `'` + username + `'`;

return connect().then(function(conn) {

return conn.query(sql_query).then(function(rows) {

console.log("HGH getUser Then");

console.log(pool);

conn.release();

return rows;

});

}).catch(function(error) {

console.log("HGH getUser Catch");

console.log(error);

throw ErrorModel.generateErrorObject(error, 500);

});

}

I am getting this issue:

conn.release is not a function when trying to release my current connection into the pool. Is my logic wrong here? My goal is to have a pool with a bunch of connections (up to a certain number) and if a user needs to query, the getConnection() function just grabs them either a free connection from the pool, or creates them one. Problem is I cannot for the life of me release it back to the pool as free..Every time I make a request with conn.end() instead of release the connection remains in the _allConnections array of the pool when I console it out, and there are absolutely no connections in the _freeConnections array.

Anyone know how I can make connections free again??

解决方案

Looking at the module's code I found the function for releasing a connection from a pool:

pool.prototype.releaseConnection = function releaseConnection(connection) {

//Use the underlying connection from the mysql-module here:

return this.pool.releaseConnection(connection.connection);

};

So if all of these functions live in the same file you could do the following in the getUser function:

replace

conn.release();

with

pool.releaseConnection(conn);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值