我想在 Node JS Express 4 中使用 node-mssql 作为 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.
自从我问和回答这个问题已经 3 年了.从那时起,一些事情发生了变化.这是我今天推荐的基于 ES6、mssql 4 和 Express 4 的新解决方案.
It's been 3 years since I asked and answered the question. Since then a few things have changed. Here's the new solution based on ES6, mssql 4 and Express 4 that I would suggest today.
这里有两个关键元素在起作用.
Two key elements are at play here.
在server.js
const express = require('express')
// require route handlers.
// they will all include the same connection pool
const set1Router = require('./routes/set1')
const set2Router = require('./routes/set2')
// generic express stuff
const app = express()
// ...
app.use('/set1', set1Router)
app.use('/set2', set2Router)
// No need to connect the pool
// Just start the web server
const server = app.listen(process.env.PORT || 3000, () => {
const host = server.address().address
const port = server.address().port
console.log(`Example app listening at http://${host}:${port}`)
})
在db.js
const sql = require('mssql')
const config = {/*...*