【问题标题】:is there any way to Connect oracledb using typescript ES6 class and module?有什么方法可以使用 typescript ES6 类和模块连接 oracledb?
【发布时间】:2019-05-16 17:31:24
【问题描述】:

我正在尝试使用 Typescript ES6 类模块实现 oracle 连接。

我已经安装了 @types/oracledb 包以及 oracledb 包。使用了 Jasmin 框架。

下面是我实现的代码。

import * as oracledb from 'oracledb';

export class ConnectionDAO{
/**
 * Connection Variable Declaration
 */
conn;

/**
 * Result Variable Declaration
 */
result;

/**
 *
 * Creates an instance of CommercialDAO.
 * To Initiate Connection and Make the connection utilized by @memberof CommercialDAO
 * @memberof CommercialDAO
 */
constructor() {
   this.conn = oracledb.getConnection({
        user: "commercial",
        password: "oracle",
        connectString: "localhost/COMMERCIALDB"
      }); 
}

public getRwCnt() {
    return new Promise(async function(resolve, reject) {
        try {
            let result = this.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
            resolve(this.result.rows.length);
        } catch (err) { // catches errors in getConnection and the query
          reject(err);
        } 
        this.conn.release();
      });
}
}

错误:

TypeError: this.conn.execute is not a function

但是在这个代码连接中,它本身并没有被存储在 'this.conn' 变量中。

是否有避免承诺和异步功能? 有没有其他解决方案可以实现这一目标?请为您提供有价值的解决方案和建议。期待样本 sn-p。

【问题讨论】:

    标签: oracle typescript protractor es6-class


    【解决方案1】:

    你的错误的真正原因

    TypeError: this.conn.execute is not a function
    

    是因为 this.conn 很可能是未定义的。添加这样的支票。

    public getRwCnt() {
      if(this.conn === undefined){
        console.log("The connection is not ready yet.");
        return;
    ... // Rest of your function
    }
    

    但这只会突出你有问题,而不是告诉你原因。

    原因是您的构造函数是严格同步的。 考虑有一个等待构造函数完成的函数。

    这是一个有效的版本:

    import * as OracleDB from 'oracledb';
    
    export class ConnectionDAO {
      /**
       * Connection Variable Declaration
       */
      public conn: OracleDB.IConnection;
      public connProm: OracleDB.IPromise<void>;
    
      /**
       * Result Variable Declaration
       */
      result;
    
      /**
       *
       * Creates an instance of CommercialDAO.
       * To Initiate Connection and Make the connection utilized by @memberof CommercialDAO
       * @memberof CommercialDAO
       */
      constructor() {
        this.connProm = OracleDB.getConnection({
          user: "hr",
          password: "hr",
          connectString: "localhost/XEPDB1"
        }).then(async (connection: OracleDB.IConnection) => {
          console.log("Connection finally created in constructor")
          this.conn = connection;
        }).catch((err: any) => {
          console.error(err.message);
        });
        console.log(" - Dumping Connection state in the end of the constructor", {conn: this.conn} , {connProm: this.connProm} );
      }
    
      public getRwCnt() {
        let me = this;
        return new Promise(async function (resolve, reject) {
          try {
            console.log(" - Dumping Connection state BEFORE waiting",{conn: me.conn} , {connProm: me.connProm} );
            await me.connProm;
            console.log(" - Dumping Connection state AFTER waiting",{connServerVersion: me.conn.oracleServerVersion } , {connProm: me.connProm} );
            let result = await me.conn.execute('SELECT count(*) FROM employees');
            resolve(result.rows);
          } catch (err) { // catches errors in getConnection and the query
            console.log("[Error] happened? - calling reject",err);
            reject(err);
          }
          if(me.conn) // Only release it it if it actually is set
            me.conn.release();
        });
      }
    }
    
    const d = new ConnectionDAO();
    
    d.getRwCnt()
      .then((result)=>{console.log("RowCount",result)})
      .catch((err)=>{console.error("Promise rejected - ",err)})
    
    console.log("Object constructor returned");
    

    用 ts-node 运行会得到这个结果

     - Dumping Connection state in the end of the constructor { conn: undefined } { connProm: Promise { <pending> } }
     - Dumping Connection state BEFORE waiting { conn: undefined } { connProm: Promise { <pending> } }
    Object constructor returned
    Connection finally created in constructor
     - Dumping Connection state AFTER waiting { connServerVersion: 1804000000 } { connProm: Promise { undefined } }
    RowCount [ [ 107 ] ]
    

    【讨论】:

      【解决方案2】:

      您似乎在函数getRwCnt() 中以错误的方式使用了this

      记住 JavaScript 中的每个函数都有自己的this

      选项1将顶部this分配给函数开头的另一个变量

      public getRwCnt() {
          let me = this; 
          return new Promise(async function(resolve, reject) {
              try {
                  let result = me.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
                  resolve(this.result.rows.length);
              } catch (err) { // catches errors in getConnection and the query
                reject(err);
              } 
              me.conn.release();
            });
      

      选项 2 使用 ES6 箭头函数

      public getRwCnt() {
      
              return new Promise(async (resolve, reject) => {
                  try {
                      let result = this.conn.execute('SELECT TESTCASEID FROM EXECUTE_TESTCASE');
                      resolve(this.result.rows.length);
                  } catch (err) { // catches errors in getConnection and the query
                    reject(err);
                  } 
                  this.conn.release();
                });
      

      【讨论】:

        【解决方案3】:

        我尝试了您的解决方案,但看起来 typescript 没有在等待调用 等待我.connectionPromise; 另外,不确定连接是否成功。我的输出低于输出。

        Inside constructor
        get Connection executed....
         - Dumping Connection state in the end of the constructor { conn: undefined } { connProm: Promise { <pending> } }
        Inside getRowNumbers function call....
        Connection state BEFORE waiting:  { conn: undefined } { connectionPromise: Promise { <pending> } }
        Object constructor returned
        
        Somehow below output lines in your code are missing for me.
        
        Connection finally created in constructor
         - Dumping Connection state AFTER waiting { connServerVersion: 1804000000 } { connProm: Promise { undefined } }
        RowCount [ [ 107 ] ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-05
          • 2020-04-30
          • 2015-11-05
          • 2019-08-29
          • 1970-01-01
          • 2020-08-05
          • 2019-12-25
          相关资源
          最近更新 更多