使用mysql2/promise的连接池因为连接没有释放,最后mysql会报Can't create more than max_prepared_stmt_count statements错误,那么它如何释放连接呢?
我的代码是这样的
1.创建连接
const mysql = require('mysql2/promise')
var connection = mysql.createPool(mysqlConfig)
global.connection = connection
2.把链接挂载到ctx上
app.use(async (ctx, next) => {
ctx.mysqlConection = global.connection
// console.log(global.connection, '99999999999')
ctx.controller = controller
ctx.service = service
ctx.are = are
ctx.iz = iz
ctx.rules = rules.rules
ctx.model = mongodb.mongoose.models;
await next()
ctx.mysqlConection.end()
})```
3. 在controller就可以使用连接
findUv: async function (ctx) {
let condition = ctx.request.body
let sql = `SELECT count AS uv FROM gugudai_count ORDER BY id ASC LIMIT 1`
console.log('******************2',ctx.mysqlConection.getConnection)
const [rows, fields] = await ctx.mysqlConection.execute(sql)
// let conne=await ctx.mysqlConection.getConnection;
// console.log(conne)
return { rows }
},
看完你的回复,看了下官网API,可能你的写法在其他包没问题,但不符合
mysql2
的实现。比如一开始链接并没有被创建,而是按需创建,并需要自己回收。mysql2