【问题标题】:NodeJS MSSQL multiple queries promisedNodeJS MSSQL 多查询承诺
【发布时间】:2019-07-31 03:08:20
【问题描述】:

我在使用mssql npm 库时遇到很多问题。

这是我的数据库类:

"use strict"
const mssql = require('mssql');
const moment = require("moment");
let pool_historian = null;
let connexion_historian = null;

function mapBarChart(array) {
    return new Promise((resolve, reject) => {
        let result = {}
        result.old = []
        result.this = []
        let currentYear = null;
        for (let i = 0; i < array.length; i++) {
            if (parseInt(moment().format("YYYY")) !== array[i].Annees) {
                result.old.push(array[i]);
            } else {
                result.this.push(array[i]);
            }
        }
        resolve(result);
    })
};

class Historian {
    constructor(data) {
        pool_historian = new mssql.ConnectionPool({
            server: data.host,
            user: data.username,
            password: data.password,
            database: data.historian_db,
            pool: {
                max: 50,
                min: 1
            }
        });
    }

    getBarChart(sensor, from, to) {
        return pool_historian.connect().then(connector => {
            return connector.query`SELECT Annees=YEAR(DateTime),Mois=MONTH(DateTime), Valeur=ROUND(sum(AnalogHistory.Value),2) FROM AnalogHistory WHERE AnalogHistory.TagName IN (${sensor}) AND Quality = 0 AND wwVersion = 'Latest' AND wwRetrievalMode = 'Full' AND DateTime >= ${from} AND DateTime <= ${to} AND AnalogHistory.Value > 0 GROUP BY YEAR(AnalogHistory.DateTime),MONTH(AnalogHistory.DateTime) ORDER BY Annees, Mois`.then(result => {
                connector.close();
                return mapBarChart(result.recordset).then(result => { return result });
                //return result.recordset;
            }).catch(err => {
                return err;
            })
        })
    }
    getLineChart() {
        return pool_historian.connect().then(connector => {
            let variable = "A_000000000000000000000000000045.PV";
            return connector.query`SELECT Annees=YEAR(DateTime),Mois=MONTH(DateTime),day=DAY(DateTime), Valeur=ROUND(sum(AnalogHistory.Value),2) FROM AnalogHistory WHERE AnalogHistory.TagName IN (${variable}) AND Quality = 0 AND wwVersion = 'Latest' AND wwRetrievalMode = 'Cyclic' AND DateTime >= '20160101 00:00:00.000' AND DateTime <= '20170809 00:00:00.000' AND AnalogHistory.Value > 0 GROUP BY YEAR(AnalogHistory.DateTime),MONTH(AnalogHistory.DateTime), Day(AnalogHistory.DateTime)ORDER BY Annees, Mois`.then(result => {
                connector.close();
                return result.recordset;
            }).catch(err => {
                return err;
            })
        })
    }

    close() {
        pool_historian.close()
    }
}

这个类用在这个“业务类”中:

const Historian = require(`${__dirname}/historian-query`)
const Fdedb = require(`${__dirname}/fdedb-query`)
const moment = require('moment');

moment.locale("fr-FR");

class Graph_Tasks {
    constructor() {
        this.historian = new Historian({ host: "192.168.1.16", username: "******", password: "w***", historian_db: "R******e" })
        this.fdedb = new Fdedb({ host: "192.168.1.16", username: "*****", password: "*****", fde_db: "S*****" })
    }

    createGraphForBuilding(code) {
        return new Promise((resolve, reject) => {
            this.fdedb.getList(code).then(list => {
                console.log(list)
                let datas = [];

                //Foreach item on the list perform these 2 queryes

                Promise.all([this.historian.getLineChart("A_000000000000000000000000000045.PV", moment().subtract(1, "years").startOf("year").format(), moment().format()), this.historian.getBarChart("A_000000000000000000000000000045.PV", moment().subtract(1, "years").startOf("year").format(), moment().format())]).then(results => {
                    let datas = []
                    datas = { "lineChart": null, "barChart": results[0] };
                    console.log(datas)
                    res.render('index', { title: 'WebGraph', message: 'Yo Yo', datas });
                })

                console.log(datas)
                resolve(datas)

            }).catch(console.log);
        });

    }
}
module.exports = Graph_Tasks;

如您所见,我正在尝试执行同步数据库请求。正如我在文档中所读到的,连接池必须让我正确地做到这一点。所以当程序到达Promise.all时,我预计这2个请求会同时启动。

但我得到一个错误:

唯一的异常产品:错误
Promise Rejection (ConnectionError: 已经连接到数据库!在连接到不同的数据库之前调用close。)
ConnectionError:已经连接到数据库!在连接到不同的数据库之前调用 close。
在 ConnectionError (d:\repositories\fde\node_modules\mssql\lib\base.js:1428:7)
在 ConnectionPool._connect (d:\repositories\fde\node_modules\mssql\lib\base.js:235:23)
在 EventEmitter.connect.PromiseLibrary (d:\repositories\fde\node_modules\mssql\lib\base.js:217:19)
在 ConnectionPool.connect (d:\repositories\fde\node_modules\mssql\lib\base.js:216:12)
在 Historian.getBarChart (d:\repositories\fde\class\historian-query.js:39:31)
在 __dirname.createGraphForBuilding.Promise.fdedb.getList.then.list (d:\repositories\fde\class\graph_tasks.js:21:188)
在 process._tickCallback (internal/process/next_tick.js:109:7)

所以我的问题是:如何调整代码以让我同时执行多个查询(每个列表项的 promise.all)?

【问题讨论】:

  • 错误提示您多次连接到数据库 - 您就是这样,因为 pool_historian.connect() 被多次调用
  • 这真的让我很困惑。那么“connectionpool”不是什么旧的多重连接?
  • 老实说,我不知道,我只是在看错误和代码:p

标签: sql-server node.js promise


【解决方案1】:

问题是你不能打开多个连接池到同一个服务器(我假设 Fdedb 正在打开另一个连接,因为你没有包含它的代码)。例如,如果您从两个不同的服务器 提取数据,那么打开两个连接池是合适的——我之前遇到过这种用例。但看起来您的两个数据库位于同一服务器(本地主机)上,因此最好只打开一个连接并将其传递给您的对象以进行查询。您可以使用普通的旧 SQL 访问同一主机上的多个数据库,请参阅:How do I query tables located in different database?

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2018-01-31
    • 2019-09-29
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多