我正在使用mssql
npm 连接到 SQL Server。当我连接到数据库并获取或发布数据时,连接尚未打开。每次请求后如何关闭连接?
这是我使用的一种请求:
router.get('/getnotification/:userid',async(req,resp,next)=>{
(async function(){
let pool = null;
try{
pool = await connection
let result = await pool.request()
.input('input_id',sql.BigInt,req.params.userid)
.query(`exec showNotification 0,@input_id`)
if(result){
resp.status(200).send(result.recordset).end;
}
// pool.close()
}catch(err){
resp.status(500).send(err).end;
// pool.close()
}
})()
})
我也在pool.close()
请求完成后使用,但下一个请求连接已关闭。
您可以创建一个用于关闭池的中间件函数,并在绑定pool
到 req obj后使用它,
const closePoolMiddleware = function (req, res, next) {
if(!req.pool) {
next("pass error to express")
}
req.pool.close()
next()
})
接着,
router.get('/getnotification/:userid',async(req,resp,next)=>{
(async function(){
let pool = null;
try{
pool = await connection
let result = await pool.request()
.input('input_id',sql.BigInt,req.params.userid)
.query(`exec showNotification 0,@input_id`)
if(result){
resp.status(200).send(result.recordset).end;
}
// pool.close()
}catch(err){
resp.status(500).send(err).end;
// pool.close()
}
})()
}, closePoolMiddleware)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句