如何在我的 Node.js 项目中完美地使用 Oracle DB

问题描述

我目前正在使用 Angular、Node.Js、express 和 Oracle 数据库开发一个网站。

我仍然不熟悉所有这些技术,我正在尽我所能!我的问题是无法导出 Oracle 数据库连接。我搜索了这个,我认为这是一个承诺的事情。我找到的唯一解决方案是每次使用新的 sql 查询时都连接到数据库,这对我来说是不可能的,因为项目很大。

有什么方法可以在单独的文件中建立数据库连接并在需要时导出吗?

解决方法

对于多用户应用程序,您应该使用连接池。您在应用启动时打开它,然后根据需要访问它 - 您无需传递任何内容。

如果在初始化例程中打开连接池:

await oracledb.createPool({
  user: dbConfig.user,password: dbConfig.password,connectString: dbConfig.connectString
});
console.log('Connection pool started');

然后任何其他需要连接的模块都可以简单地做:

conn = await oracledb.getConnection();
result = await conn.execute(statement,binds,opts);
await conn.close();

阅读 node-oracledb 中的连接池、大小和线程 Connection Pooling 上的文档。

另请参阅系列 Build REST APIs for Node.js 及其代码 https://github.com/oracle/oracle-db-examples/tree/master/javascript/rest-api。尤其要注意 database.js