简体   繁体   English

将 NodeJ 连接到 Oracle 数据库

[英]Connect NodeJs to Oracle DB

Hello I am a beginner in nodejs and I would like to connect to a remote oracle db.您好,我是 nodejs 的初学者,我想连接到远程 oracle 数据库。

Here is the code:这是代码:

   const express = require('express')

const oracledb = require('oracledb')
const app = express()
const port = 3000

oracledb.getConnection(
  {
    user          : "xxx",
    password      : "xxx",
    connectString : "(tns names connection string)))"
  },
  oracledb.connExecute
)
  



app.get('/', (req, res) => {
    if(connExecute == true) {
      console.log("Conexiune reusita");
      
    } else {
      console.log("Conexiune esuata");
    }
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

When I enter the command node index.js in the cmd I get this error:当我在 cmd 中输入命令 node index.js 时,出现此错误:

 Example app listening on port 3000
node:internal/process/task_queues:96
    runMicrotasks();
    ^

Error: NJS-009: invalid number of parameters
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I have installed oracledb with npm.我已经用 npm 安装了 oracledb。 Can you please tell me what I am doing wrong or give me and working example.你能告诉我我做错了什么或给我和工作的例子。 Thanks谢谢

You missed to await your synchronous call when calling the getConnection function.您在调用 getConnection 函数时错过了等待同步调用。 As it takes some time to connect to database, the code below this line executes without waiting for connection to establish.由于连接数据库需要一些时间,因此该行下面的代码无需等待连接建立即可执行。

Also, you can simply pass a single parameter for connection using the configs to getConnection() function.此外,您可以使用配置将单个参数简单地传递给 getConnection() 函数。

Simply remove the second parameter of getConnection.只需删除getConnection 的第二个参数。

const connection = await oracledb.getConnection(
  {
      user          : "xxx",
      password      : "xxx",
      connectString : "(tns names connection string)))"
   }
 );
 if (connection) {
    console.log("Successfully connected to DB!");
 }


 app.get('/', (req, res) => {
     if(connection) {
       console.log("Conexiune reusita");
  
     } else {
       console.log("Conexiune esuata");
     }
 })

 app.listen(port, () => {
     console.log(`Example app listening on port ${port}`)
 })

Alternatively,或者,

As suggested by Matt in the comments, you can also use正如马特在评论中所建议的那样,您也可以使用

oracledb.getConnection(
  {
      user          : "xxx",
      password      : "xxx",
      connectString : "(tns names connection string)))"
   }
 ).then((connection) => {
    if (connection) {
    console.log("Successfully connected to DB!");
    }
 }).catch((err) => {console.log(`Conexiune esuata! ${err}`);})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM