我正在使用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。
答案 0 :(得分:0)
我在使用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,我们确保在服务器启动之前我们已建立连接。它可能会减慢应用程序的启动速度,因为它仍然必须连接,但是一旦启动,我们一切就绪!