node-mssql - 连接已关闭

时间:2017-10-13 14:00:26

标签: sql-server node.js azure

我使用带有mssql库的node typescript将数据插入到我的Azure服务器中的表中。我创建了一个全局连接池,在构造函数中初始化它,然后从路由服务连接到它。但是,它显示错误

  

ConnectionError:连接在ActionService.insertion“,”...在新的ActionService“,”...在新的AppDataServices“处关闭。

我不知道在哪里打破了全局池和路由服务之间的逻辑连接。我的SQL查询可能有误,但主要是关于与数据库的连接。

以下是我的代码:

app-data-services.ts(全局连接池):

import * as mssql from 'mssql';
import { AppConfig } from '../config';
import { ActionService } from './data-services';
import { Logger, LoggerFactory } from '../common';

export class AppDataServices {
  private static readonly LOGGER: Logger = LoggerFactory.getLogger();

  private db: any;

  public actionService: ActionService;

  constructor(private appConfig: AppConfig) {
    this.initConnectionPool();
    this.actionService = new ActionService(this.db, AppDataServices.LOGGER);
  }

  private initConnectionPool() {
    this.db = new mssql.ConnectionPool({
      user: this.appConfig.mssqlUsername,
      password: this.appConfig.mssqlPassword,
      server: this.appConfig.mssqlServer,
      database: this.appConfig.mssqlDatabase,
      // If you are on Microsoft Azure, you need this:
      options: { encrypt: true }
    }, (err: any) => {
      if (err) AppDataServices.LOGGER.error('MSSQL error', err);
    });
  }    
} 

action-service.ts(路由数据服务):

import * as mssql from 'mssql';
import { Logger, LoggerFactory } from '../../../common';

export class ActionService {
  private static readonly LOGGER: Logger = LoggerFactory.getLogger();

  constructor (private db: any, private logger: any) {
    this.insertion();
  }

  insertion() {
    const request = new mssql.Request(this.db);
    request.query(
      `
        INSERT INTO dbo.action
          (timestamp, result, description, request_endpoint, request_payload, response_status, response_payload, actualAmount, rule_id, lendbook_id)
        SELECT t1.start, 'SUCCESS', NULL, '/lendbook/usd', NULL, '200', NULL, t1.originalAmount, t1.id, t2.id
        FROM dbo.rule t1, dbo.lendbook t2
        INNER JOIN t2.id = t1.id
      `, (err, result) => {
        if (err) {
          console.error(err);
          return;
        }
        return result.recordsets[0];
      });
  }
}

0 个答案:

没有答案