node.js - Node.js oracledb 模块——类型错误:无法读取未定义的属性“关闭”
问题描述
我正在尝试使用 Oracledb npm for Nodejs 运行简单的 SQL 语句。这在过去没有问题,但突然我在不同的环境中遇到了这个错误。可能是因为别名?我不确定。
导致问题的线路的目标是在连接完成或失败后关闭连接。我直接在 Oracle 的文档中找到了逻辑:http: //oracle.github.io/node-oracledb/doc/api.html#connectionclose
真的很感激任何帮助!
const oracledb = require('oracledb');
const async = require('async');
const {getAwsSecret} = require('./awssecret');
var alias = "";
async function initialize() {
// Set Oracle Pool Settings
let hrPool = {
poolMin: 10,
poolMax: 10,
poolIncrement: 0
}
var secret = await getAwsSecret('MAIN');
const secretJSON = JSON.parse(secret);
hrPool.user = secretJSON[process.env.CURENV + 'username'];
hrPool.password = secretJSON[process.env.CURENV + 'password'];
hrPool.connectString = secretJSON[process.env.CURENV + 'host'] + '/' + secretJSON[process.env.CURENV + 'dbname'];
hrPool.poolAlias = secretJSON.alias;
alias = secretJSON.alias;
try {
await oracledb.createPool(hrPool);
} catch (err) {
console.log(err);
}
}
module.exports.initialize = initialize;
async function close() {
await oracledb.getPool().close();
}
module.exports.close = close;
async function simpleExecute(statement, binds = [],clientdetails = [], opts = {}) {
let conn;
opts.outFormat = oracledb.OBJECT;
opts.autoCommit = true;
try {
// Get Connection
conn = await oracledb.getConnection(alias);
// Run Query
const result = await conn.execute(statement, binds, opts);
///////////// POST EXECUTION HANDLING /////////////
if (conn) { // conn assignment worked, need to close
try {
// Close Connection
await conn.close();
// Return Result
return result;
} catch (err) {
console.log(err);
}
}
///////////// POST EXECUTION HANDLING /////////////
} catch (err) {
await conn.close();
}
}
module.exports.simpleExecute = simpleExecute;
错误:
TypeError: Cannot read property 'close' of undefined 2021-04-23T14:36:51.269-04:00 at
Object.simpleExecute (/usr/src/app/services/database.js:59:18)
解决方案
如果获取连接时出错,您的 catch 块调用conn.close()
没有有效的conn
. 这给出了您看到的错误。这可能不是唯一的原因,但整理代码会有所帮助。
你conn.close()
可能只有一个finally()
街区一次。查看example.js 之类的示例,例如:
let connection;
try {
connection = await oracledb.getConnection(dbConfig);
result = await connection.execute(sql, binds, options);
console.dir(result, { depth: null });
} catch (err) {
console.error(err);
} finally {
if (connection) {
try {
await connection.close();
} catch (err) {
console.error(err);
}
}
}
其他一些提示:
- 如果您的代码要连续执行几条语句,则不要在每个语句周围执行
getConnection()
/close()
。这会影响池的可伸缩性,因为共享池资源存在一些锁定,并且会在整个步骤中添加额外的代码。 - 避免总是承诺。如果不必要地这样做,这可能会破坏事务一致性并增加开销。
drainTime
在调用中使用显式pool.close()
以确保它已关闭,请参阅webapp.js。
推荐阅读
- date - 映射中的 Elasticsearch 日期格式
- java - 使用 Java 的 lambda 和流将文本文件映射到 Map
- javascript - 如何处理动态呈现的 html 数据的点击事件?
- visual-studio-code - 当我输入 VSCode 时如何做到这一点,我的文本不会一直排在一行
- java - 已定义变量但 java 找不到它/“找不到符号”错误
- amazon-web-services - Amazon EC2 Windows AMI 启动缓慢
- testing - 用 jest 测试 axios 拦截器
- java - 在触摸屏上按下按钮时,JavaFX 按钮 onAction 属性不会触发
- java - 相同的while循环,但将条件放在while循环中并不能满足它的需要
- python - 使用pyodbc从python中的Access数据库读取