首页 > 解决方案 > 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。

标签: node.jssql-server

解决方案


我在使用 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,我们可以确保在服务器启动之前建立连接。它可能会减慢应用程序的启动速度,因为它仍然需要连接,但是一旦启动,我们就准备好了!


推荐阅读