You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用Tedious连接Oracle数据库报错:Connection lost - socket hang up

问题解决:Node.js连接Oracle数据库报错'ConnectionError: Connection lost - socket hang up'

核心问题

你用错了驱动库:Tedious是专门为Microsoft SQL Server开发的Node.js驱动,完全不支持Oracle数据库,这就是导致连接报错的根本原因。

正确解决方案

改用Oracle官方提供的node-oracledb驱动(或其他Oracle兼容驱动),同时正确配置Oracle所需的SID参数。

步骤1:安装Oracle兼容驱动

执行以下命令安装官方驱动:

npm install oracledb

步骤2:修改连接代码

替换原有的Tedious代码为以下内容:

const fs = require('fs');
const path = require('path');
const oracledb = require('oracledb');

// 读取配置文件
let credsDb = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'creds_db_cmo.json')).toString());

// 配置Oracle连接参数
async function connectToOracle() {
  let connection;
  try {
    connection = await oracledb.getConnection({
      user: credsDb.user,
      password: credsDb.password,
      connectString: `${credsDb.server}:${credsDb.port || 1521}/${credsDb.sid}` // 使用SID拼接连接字符串
      // 如果用Service Name,格式替换为:`${credsDb.server}:${credsDb.port || 1521}/${credsDb.serviceName}`
    });
    console.log('DB Connected');
  } catch (err) {
    console.error('Error:', err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error('Error closing connection:', err);
      }
    }
  }
}

// 执行连接
connectToOracle();

步骤3:更新配置文件

在creds_db_cmo.json中添加port和sid(或serviceName)字段:

{
  "user" : "your_oracle_username",
  "password": "your_oracle_password",
  "server": "your_oracle_host",
  "port": 1521,
  "sid": "your_oracle_sid",
  // 若使用Service Name,替换sid为:"serviceName": "your_oracle_service_name"
  "database": "your_database_name" // 部分场景可省略,以connectString配置为准
}

额外排查点

  • 确认Oracle服务器的1521端口对外开放,本地服务器能正常连通Oracle主机
  • 检查Oracle监听配置(listener.ora)是否正常,确保SID/Service Name已正确注册
  • 若Oracle启用了加密连接,需在驱动配置中添加对应加密参数

内容的提问来源于stack exchange,提问作者Gexs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:08:22