有什么方法可以使用typescript ES6类和模块连接oracledb?

yyyllmsg  于 2023-04-29  发布在  Oracle
关注(0)|答案(4)|浏览(194)

我正在尝试使用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

但在这个代码连接本身没有得到存储在'这。连接变量。
有没有办法避免promise和async函数?是否有其他解决方案来实现这一点?请提供您宝贵的解决方案和建议。应为示例代码段。

pbwdgjma

pbwdgjma1#

你犯错误的真正原因

TypeError: this.conn.execute is not a function

是因为这个。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 ] ]
t3psigkw

t3psigkw2#

似乎你用错误的方式在函数getRwCnt()中使用this
记住JavaScript中的每个函数都有self 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();
          });
tmb3ates

tmb3ates3#

我尝试了你的解决方案,但看起来像 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 ] ]
mfpqipee

mfpqipee4#

我也有同样的问题。替换了我的导入:

import * as oracledb from 'oracledb';

import oracledb from 'oracledb';

帮我修好了

相关问题