【发布时间】:2021-10-28 19:15:10
【问题描述】:
我正在创建 Express JS 作为我的 API 服务器,使用繁琐的方法连接到我的 SQL Server 数据库。
目前,在每个请求逻辑中,我都会创建一个新的繁琐的 Connection 对象,连接到 DB,执行查询,然后关闭连接。
import { Connection } from 'tedious';
export class Controller {
all(_: Request, res: Response): void {
const connection = new Connection(getConfig()); // create a new connection everytime
connection.on('connect', (err) => {
if (err) {
console.log('Connection Failed');
throw err;
}
getProducts(connection, _, res); // in there at the end, will call connection.close()
});
connection.connect();
}
import { Request, Response } from 'express';
import { Connection, Request as SqlReq } from 'tedious';
export default function getProducts(connection: Connection, _: Request, res: Response) {
const query = `SELECT * FROM Production.Product FOR JSON PATH;`;
let resultJson = ''; // prepare this result in return from SQL query
const sqlReq = new SqlReq(query, (err, _) => {
if (err) {
throw err;
}
// when request finished
connection.close();
res.json(JSON.parse(resultJson));
});
每次为新的 API 调用创建连接、连接和关闭是好还是坏?如果有更好的方法来处理连接,我可以提供任何参考或示例吗?
【问题讨论】: