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

将Java+Rhino JS服务重构为Node.js,需实现同步数据库查询功能

我明白你要的是和原来Rhino环境里完全一致的同步数据库查询体验——不用异步回调、不用async/await包裹,直接像普通同步函数那样调用赋值对吧?下面以MySQL为例(其他数据库思路完全通用),给你一步步实现符合需求的executeRowsetParam函数:

实现Node.js同步数据库查询(对标Rhino DB操作)

1. 选择支持同步查询的数据库驱动

Node.js生态里异步是主流,但不少数据库驱动都提供了同步API。这里推荐用**mysql2**,它性能稳定、文档完善,原生支持同步查询:

先安装依赖:

npm install mysql2

2. 封装核心查询函数

我们要封装出和你原来逻辑对齐的函数,返回的对象还要支持getRow(index).getValue(columnName)这样的调用(甚至兼容你示例里列名带空格的情况):

const mysql = require('mysql2');

// 初始化数据库连接(根据你的实际配置修改)
const dbConnection = mysql.createConnection({
  host: '你的数据库地址',
  user: '数据库用户名',
  password: '数据库密码',
  database: '目标数据库名'
});

function executeRowsetParam(sql, params) {
  // 使用mysql2的同步查询API,直接获取结果集
  const [rows] = dbConnection.execute(sql, params);

  // 返回模拟原Rhino风格的结果对象
  return {
    // 根据索引获取单条行数据
    getRow(index) {
      const targetRow = rows[index] || {};
      return {
        // 获取指定列的值,自动去除列名两端空格(兼容你示例里的"user_name ")
        getValue(columnName) {
          return targetRow[columnName.trim()] ?? null;
        }
      };
    },
    // 可选扩展:获取所有行数据
    getAllRows() {
      return rows.map(row => ({
        getValue: (col) => row[col.trim()] ?? null
      }));
    }
  };
}

3. 按照你的需求直接调用

现在就可以完全复刻你原来的代码风格,不用做任何异步适配:

// 查询用户名称
var userNameResult = executeRowsetParam('SELECT user_name FROM users where user_id = ?', ["123"]);
// 验证是否为管理员
if(userNameResult.getRow(0).getValue("user_name ") === "admin"){ 
  console.log("已检测到管理员用户,执行对应逻辑...");
  // 这里写你的业务代码
}

4. 实用细节与扩展

连接池优化(服务端必备)

如果是在Node.js服务端使用,建议用连接池代替单连接,避免连接耗尽问题。mysql2的连接池同样支持同步操作:

const dbPool = mysql.createPool({
  host: '你的数据库地址',
  user: '数据库用户名',
  password: '数据库密码',
  database: '目标数据库名',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 修改executeRowsetParam里的查询逻辑
function executeRowsetParam(sql, params) {
  const conn = dbPool.getConnectionSync();
  try {
    const [rows] = conn.execute(sql, params);
    // ... 后面的返回逻辑不变
    return {
      getRow(index) {
        const targetRow = rows[index] || {};
        return {
          getValue(columnName) {
            return targetRow[columnName.trim()] ?? null;
          }
        };
      }
    };
  } finally {
    conn.release();
  }
}

异常处理

同步查询出错会直接抛出异常,记得用try/catch包裹避免服务崩溃:

try {
  const result = executeRowsetParam('SELECT * FROM non_existent_table', []);
} catch (error) {
  console.error("数据库查询出错:", error.message);
  // 这里可以加错误日志、告警等逻辑
}

多表关联查询场景

如果需要查询多个相关数据,直接多次调用函数即可,完全同步执行:

// 先查用户基础信息
const userInfo = executeRowsetParam('SELECT user_id, user_name FROM users WHERE user_id = ?', ["123"]);
const userId = userInfo.getRow(0).getValue("user_id");

// 再查该用户的订单总数
const orderCountResult = executeRowsetParam('SELECT COUNT(*) AS order_count FROM orders WHERE user_id = ?', [userId]);
const orderCount = orderCountResult.getRow(0).getValue("order_count");

console.log(`用户${userInfo.getRow(0).getValue("user_name")}共有${orderCount}条订单`);

这样就完美适配了你从Rhino转到Node.js的需求,既保留了熟悉的同步调用风格,又符合Node.js的生态规范~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:07:36