最近我正在用
Oracle SQL Databse
配置 node.js
。我的数据库连接示例查询是:
import * as oracledb from 'oracledb';
export class OracleSQL {
private static conn;
static async connect() {
this.conn: await oracledb.getConnection({
connectString: "host:port/schema",
user : "username",
password : "********"
});
// TODO: add some condition to verify database connected successfully
// if (connection is established) {
console.log('Database connected successfully');
return true;
// }
// TODO: if connection not established for any reason and throwing error
// How to handle this error ?
// is that a simple "Try...Catch" method or some other way ?
}
static async query(queryStr) {
// TODO: add some condition to verify connection is still alive or not
if (!this.conn) {
let res = await this.connect()
if (res) {
return await this.conn.execute(queryStr);
}
} else {
return await this.conn.execute(queryStr);
}
}
static async close() {
// TODO: add some condition to verify connection already established or not
// if (connection is established) {
await this.conn.close()
.then(() => {
console.log('Database disconnected successfully');
this.conn = null;
return true;
});
// }
}
}
我想在这里添加两个目标:
我查阅了 Node.js Oracle Connection、npm oracledb 文档。但没有找到任何有价值的信息。
经过大量研究后我发现,
Oracle DB 连接对象有一个属性
conn._impl.nscon.connected
,其中包含连接建立的布尔值。
import * as oracledb from 'oracledb';
const conn = await oracledb.getConnection({
connectString: "host:port/schema",
user : "username",
password : "********"
});
if ( conn._impl.nscon.connected ) {
console.log('Database connected successfully');
}
这是验证连接已建立或活动状态的有效方法吗?
我不知道。你有什么想法吗?
我建议使用
try/catch
方法来验证连接建立和错误处理
import * as oracledb from 'oracledb';
export class OracleSQL {
private static conn;
static async connect() {
try{
this.conn : await oracledb.getConnection({
connectString: "host:port/schema",
user : "username",
password : "********"
});
console.log('Database connected successfully');
return true;
}catch(e){
console.log('Database connection failed, Reason:',e.message);
return false;
}
}
static async query(queryStr) {
if (!this.conn) {
let res = await this.connect()
if (res) {
return await this.conn.execute(queryStr);
}
} else {
return await this.conn.execute(queryStr);
}
}
static async close() {
if (this.conn) {
try{
await this.conn.close()
console.log('Database disconnected successfully');
this.conn = null;
return true;
}catch(e){
console.log("Database disconnection failed, Reason", e.message);
}
}
}
}