有没有办法使用打字稿ES6类和模块连接oracledb



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

我已经安装了@types/oracledb软件包以及oracledb软件包。使用茉莉框架。

下面是我实现的代码。

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"变量中。

有没有办法避免承诺和异步功能?还有其他解决方案可以实现这一目标吗?请为您提供有价值的解决方案和建议。期待示例代码段。

错误的实际原因

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 ] ]

似乎您在函数 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();
          });

我尝试了您的解决方案,但看起来打字稿没有等待调用等着我.连接承诺;另外,不确定连接是否成功。我得到的输出低于。

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 ] ]

我遇到了同样的问题。已替换我的导入:

import * as oracledb from 'oracledb';

import oracledb from 'oracledb';

为我修复了它

最新更新