问题描述
我想在节点JS Express 4中使用作为MSSQL数据库连接器Web应用程序。路由处理器逻辑在单独的文件中处理。
I want to use node-mssql as a MSSQL database connector in a Node JS Express 4 web application. Route handler logic is handled in separate files.
如何创建单个/全局连接池并将其用于处理路由逻辑的多个文件?我不想在每个路由处理函数/文件中创建一个新的连接池。
How do I create a single/global connection pool and use it across several files where route logic is handled? I don't want to make a new connection pool in each route handler function/file.
推荐答案
我实际上问了自己回答,因为我相信我有一个值得分享的答案,我在其他地方找不到文件化的解决方案。同样在几个问题(,,)在node-mssql中讨论这个主题。
I actually asked the question to answer it myself, because I believe I had an answer that was worth to share and I couldn't find a documented solution elsewhere. Also in a few issues (#118, #164, #165) at node-mssql this topic is discussed.
这是我的解决方案:
在 server.js
var express = require('express');
var sql = require('mssql');
var config = {/*...*/};
//instantiate a connection pool
var cp = new sql.Connection(config); //cp = connection pool
//require route handlers and use the same connection pool everywhere
var set1 = require('./routes/set1')(cp);
var set2 = require('./routes/set2')(cp);
//generic express stuff
var app = express();
//...
app.get('/path1', set1.get);
app.get('/path2', set2.get);
//connect the pool and start the web server when done
cp.connect().then(function() {
console.log('Connection pool open for duty');
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
}).catch(function(err) {
console.error('Error creating connection pool', err);
});
在 routes / set1.js
var sql = require('mssql');
module.exports = function(cp) {
var me = {
get: function(req, res, next) {
var request = new sql.Request(cp);
request.query('select * from test', function(err, recordset) {
if (err) {
console.error(err);
res.status(500).send(err.message);
return;
}
res.status(200).json(recordset);
});
}
};
return me;
};
这篇关于如何在Express 4 Web应用程序中跨多个路由使用单个mssql连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!