node.js - Nodejs MSSQL 包慢
问题描述
我正在使用该MSSQL
包连接到 SQL Server。我已经让它工作了,但检索几行也非常慢。
这是我的代码:
var express = require('express');
var app = express();
var date
app.get('/', function (req, res) {
date=Date.now()
var sql = require("mssql/msnodesqlv8")
const config = {
user: 'sa',
password: 'PASS',
server: 'localhost\\SERVER', // You can use 'localhost\\instance' to connect to named instance
database: 'DATABASE',
pool: {
max: 10,
min: 5,
idleTimeoutMillis: 30000
}
}
new sql.ConnectionPool(config).connect().then(pool => {
return pool.query('select field1 from TABLE1')
}).then(result => {
console.dir(result)
console.dir('This query took ' + (Date.now() - date) + 'ms to return ' + result.recordset.length + ' rows!');
}).catch(err => {
// ... error checks
})
});
var server = app.listen(3000, function () {
console.log('Server is running..');
});
输出是:
{field1 :'row1'} ............ {field1:'row18'}
'This query took 5847ms to return 18 rows!'
仅检索 18 行需要花费大量时间。
这是因为我在 Windows 10 中使用免费的 SQL Server Express 版本吗?我打算处理大量数据,而这些数据需要 SQL Server 数据库,所以我不能使用 MongoDB。
解决方案
我在使用 Typescript 时遇到了这个问题,这是我解决它的方法,但不确定它是否是好的做法。
首先,我将配置提取到它自己的文件中
import mssql from 'mssql';
const dbconfig = {
server: 'u',
user: 'u',
password: 'u',
database: 'u',
options: { encrypt: true },
pool: {
min: 5
}
};
export const db = new mssql.ConnectionPool(dbconfig);
其次,我的路径也是它自己的文件,这就是它的外观
import express from 'express';
import mssql from 'mssql';
const router = express.Router();
export const route = (connection: any) => { // Note I am passing the connection here?
router.get('/', (req: any, res: any, next: any) => {
(async () => {
try {
const request = new mssql.Request(connection);
const { recordset: cool } = await request.query(
'Select * from tbl_categories'
);
res.send(cool);
} catch (error) {
next(error);
}
})();
});
return router
}
好的好的,最后一步连接是在入口文件 app.ts / server.ts 上创建的
import express from 'express';
import * as router from '../src/routes/test';
import morgan from 'morgan';
import { db } from './config.ts/dbconfig';
(async () => {
const connection = await db.connect(); // Connection is created here
const app = express();
const port = process.env.PORT || 4000;
app.use(morgan('dev'));
app.use('/tests', router.route(connection)); //Connection is passed to the route, problem solved
app.get('/', (req, res) => {
res.send('Yey!');
});
app.listen(port, () => {
console.log('server is running');
});
})();
因此,通过在此处使用 async 和 await,我们可以确保在服务器启动之前建立连接。它可能会减慢应用程序的启动速度,因为它仍然需要连接,但是一旦启动,我们就准备好了!
推荐阅读
- java - 无法在使用 Appium 和 Java for Android 移动设备的混合应用程序中定位元素
- json - 以 xamarin 形式反序列化数据集
- angularjs - 带有参数的angularjs翻译,也被翻译了
- java - Integer.toString(char) 的相反方法
- visual-studio - Visual Studio - SDL2 - 在 libpng 16 中找不到入口点
- javascript - 如何在 html 选择中使用 bootstrap 4 弹出框
- oracle - Docker Oracle 数据库 - 无法覆盖凭证的 ENV 变量
- mysql - MySQL映射表插入约束不起作用
- css - Bootstrap 4 在 iphone 上保持 cols 连续的问题
- permissions - 文档类型而不是节点的精细权限 Umbraco