/*** encoding: utf-8* 版权所有 2025 ©涂聚文有限公司 ®* 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎* 描述: https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html ojdbc11* Author    : geovindu,Geovin Du 涂聚文.* IDE       : IntelliJ IDEA 2024.3.6 Java 17* # database  : Oracle21c,MySQL 9.0,SQL Server 2019,PostgreSQL 17.1 Neo4j* # OS        : window10* Datetime  : 2025 - 2025/7/13 - 14:25* User      : geovindu* Product   : IntelliJ IDEA* Project   : oracledemo* File      : DuOracleHelper.java* explain   : 学习  类**/package Geovin.UtilitieDB;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Driver.*;
import java.util.HashMap;
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;/***geovindu,Geovin Du*/
public class DuOracleHelper {/*** 命令类型枚举*/public enum CommandType {TEXT, STORE_PROCEDURE}/*** 参数方向枚举*/public enum ParameterDirection {IN, OUT}/*** 数据库参数类*/public static class Parameter {public String name; // 注意:这个字段在简单查询中可能不需要,但保留用于存储过程public Object value;public ParameterDirection direction;public int type;/*** 新增三参数构造函数(用于简单查询)* @param value* @param direction* @param type*/public Parameter(Object value, ParameterDirection direction, int type) {this.name = null; // 简单查询不需要参数名this.value = value;this.direction = direction;this.type = type;}/*** 保留原有的四参数构造函数(用于存储过程)* @param name* @param value* @param direction* @param type*/public Parameter(String name, Object value, ParameterDirection direction, int type) {this.name = name;this.value = value;this.direction = direction;this.type = type;}}/*** 数据列类*/public static class DataColumn {public String columnName;public Object value;public DataColumn(String columnName, Object value) {this.columnName = columnName;this.value = value;}@Overridepublic String toString() {return "\"" + columnName + "\": " + (value == null ? "null" : "\"" + value.toString() + "\"");}}/*** 数据行类*/public static class DataRow {private List<DataColumn> columns = new ArrayList<>();public void addColumn(DataColumn column) {columns.add(column);}public DataColumn getColumn(String columnName) {for (DataColumn column : columns) {if (column.columnName.equalsIgnoreCase(columnName)) {return column;}}return null;}public List<DataColumn> getColumns() {return columns;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder("{");for (int i = 0; i < columns.size(); i++) {sb.append(columns.get(i).toString());if (i < columns.size() - 1) {sb.append(", ");}}sb.append("}");return sb.toString();}}/*** 数据表类*/public static class DataTable {private List<DataRow> rows = new ArrayList<>();public void addRow(DataRow row) {rows.add(row);}public List<DataRow> getRows() {return rows;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder("[");for (int i = 0; i < rows.size(); i++) {sb.append(rows.get(i).toString());if (i < rows.size() - 1) {sb.append(",\n");}}sb.append("]");return sb.toString();}}/*** 数据集类*/public static class DataSet {private List<DataTable> tables = new ArrayList<>();public void addTable(DataTable table) {tables.add(table);}public List<DataTable> getTables() {return tables;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder("{");for (int i = 0; i < tables.size(); i++) {sb.append("\"table").append(i).append("\": ").append(tables.get(i).toString());if (i < tables.size() - 1) {sb.append(",\n");}}sb.append("}");return sb.toString();}}/*** 从JSON配置文件读取数据库连接信息* @param configFilePath 配置文件路径* @return 包含数据库连接信息的Map* @throws IOException 如果读取文件或解析JSON出错*/public static Map<String, String> getConnectionInfo(String configFilePath) throws IOException {StringBuilder content = new StringBuilder();try (BufferedReader reader = new BufferedReader(new FileReader(configFilePath))) {String line;while ((line = reader.readLine()) != null) {content.append(line);}}// 解析JSON配置Map<String, String> config = new HashMap<>();// 简单解析,忽略JSON格式的复杂性String[] pairs = content.toString().replaceAll("[{}\"]", "").split(",");for (String pair : pairs) {String[] keyValue = pair.split(":");if (keyValue.length == 2) {config.put(keyValue[0].trim(), keyValue[1].trim());}}// 验证必要的配置项if (!config.containsKey("host") ||!config.containsKey("port") ||!config.containsKey("serviceName") ||!config.containsKey("user") ||!config.containsKey("password")) {throw new IOException("配置文件缺少必要的连接参数");}return config;}/*** 创建Oracle数据库连接* @param configFilePath 配置文件路径* @return Connection对象* @throws SQLException 如果连接数据库失败* @throws IOException 如果读取配置文件失败*/public static Connection getConnection(String configFilePath) throws SQLException, IOException {Map<String, String> config = getConnectionInfo(configFilePath);try {// 加载Oracle驱动Class.forName("oracle.jdbc.OracleDriver");} catch (ClassNotFoundException e) {throw new SQLException("找不到Oracle JDBC驱动", e);}// 构建Oracle连接字符串String host = config.get("host");String port = config.get("port");String serviceName = config.get("serviceName");String user = config.get("user");String password = config.get("password");if (host == null || port == null || serviceName == null || user == null || password == null) {throw new IOException("配置文件缺少必要的连接参数");}// 构建连接URL  jdbc:oracle:thin:@//localhost:1521/TechnologyGameString url = String.format("jdbc:oracle:thin:@//%s:%s/%s",config.get("host"),config.get("port"),config.get("serviceName"));// 创建连接return DriverManager.getConnection(url, config.get("user"), config.get("password"));}/*** 执行查询并返回DataSet* @param configFilePath* @param commandType* @param commandText* @return* @throws Exception*/public static DataSet executeDataSet(String configFilePath, CommandType commandType, String commandText) throws Exception {return executeDataSet(configFilePath, commandType, commandText, new Parameter[0]);}/*** 执行查询并返回DataSet,带参数* @param configFilePath* @param commandType* @param commandText* @param parameters* @return* @throws Exception*/public static DataSet executeDataSet(String configFilePath, CommandType commandType, String commandText, Parameter... parameters) throws Exception {try (Connection conn = getConnection(configFilePath)) {return executeDataSet(conn, commandType, commandText, parameters);}}/*** 执行查询并返回DataSet* @param connection* @param commandType* @param commandText* @return* @throws Exception*/public static DataSet executeDataSet(Connection connection, CommandType commandType, String commandText) throws Exception {return executeDataSet(connection, commandType, commandText, new Parameter[0]);}/***  * 执行查询并返回DataSet,带参数* @param connection* @param commandType* @param commandText* @param parameters* @return* @throws Exception*/public static DataSet executeDataSet(Connection connection, CommandType commandType, String commandText, Parameter... parameters) throws Exception {DataSet ds = new DataSet();System.out.println("开始执行查询: " + commandText);if (commandType == CommandType.TEXT) {try (PreparedStatement pstmt = connection.prepareStatement(commandText)) {// 设置参数for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];if (p.direction == ParameterDirection.IN) {System.out.println("设置输入参数 " + (i + 1) + ": " + p.name + " = " + p.value);pstmt.setObject(i + 1, p.value, p.type);}}// 执行查询try (ResultSet rs = pstmt.executeQuery()) {System.out.println("执行SQL查询成功,开始处理结果集");DataTable dt = convertResultSetToDataTable(rs);System.out.println("结果集转换为DataTable,包含 " + dt.getRows().size() + " 行");ds.addTable(dt);}}} else if (commandType == CommandType.STORE_PROCEDURE) {StringBuilder paramPlaceholders = new StringBuilder();for (int i = 0; i < parameters.length; i++) {paramPlaceholders.append("?, ");}if (paramPlaceholders.length() > 0) {paramPlaceholders = new StringBuilder(" ( " + paramPlaceholders.substring(0, paramPlaceholders.length() - 2) + " ) ");}String sql = "{ call " + commandText + paramPlaceholders + " }";System.out.println("准备调用存储过程: " + sql);try (CallableStatement proc = connection.prepareCall(sql)) {// 设置参数for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];System.out.println("设置参数 " + (i + 1) + ": " + p.name + " (方向: " + p.direction + ", 类型: " + p.type + ")");if (p.direction == ParameterDirection.IN) {proc.setObject(i + 1, p.value, p.type);} else if (p.direction == ParameterDirection.OUT) {proc.registerOutParameter(i + 1, p.type);}}// 执行存储过程System.out.println("开始执行存储过程...");boolean hasResultSet = proc.execute();System.out.println("存储过程执行完成,是否有结果集: " + hasResultSet);// 处理所有结果集int resultSetCount = 0;while (hasResultSet) {try (ResultSet rs = proc.getResultSet()) {System.out.println("处理结果集 #" + (resultSetCount + 1));if (rs != null) {DataTable dt = convertResultSetToDataTable(rs);System.out.println("结果集 #" + (resultSetCount + 1) + " 包含 " + dt.getRows().size() + " 行");ds.addTable(dt);resultSetCount++;} else {System.out.println("结果集 #" + (resultSetCount + 1) + " 为空");}}hasResultSet = proc.getMoreResults();System.out.println("是否还有更多结果集: " + hasResultSet);}// 处理输出参数System.out.println("开始处理输出参数...");for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];if (p.direction == ParameterDirection.OUT) {p.value = proc.getObject(i + 1);System.out.println("输出参数 " + (i + 1) + " (" + p.name + ") 的值: " + p.value);// 特殊处理 Oracle 游标if (p.type == oracle.jdbc.OracleTypes.CURSOR) {System.out.println("检测到游标参数,尝试获取结果集...");// 使用 Oracle 特定的 API 获取游标oracle.jdbc.OracleCallableStatement oracleProc = (oracle.jdbc.OracleCallableStatement) proc;ResultSet rs = oracleProc.getCursor(i + 1);if (rs != null) {System.out.println("成功获取游标结果集,开始转换...");DataTable dt = convertResultSetToDataTable(rs);System.out.println("游标结果集包含 " + dt.getRows().size() + " 行");ds.addTable(dt);// 关闭结果集rs.close();} else {System.out.println("游标结果集为空");}}}}System.out.println("处理了 " + resultSetCount + " 个结果集和 " + parameters.length + " 个输出参数");}} else {throw new IllegalArgumentException("不支持的命令类型: " + commandType);}System.out.println("DataSet 包含 " + ds.getTables().size() + " 个表,总共 " +ds.getTables().stream().mapToInt(t -> t.getRows().size()).sum() + " 行数据");// 打印详细数据结构(调试用)if (ds.getTables().size() > 0) {System.out.println("第一个表的结构: " + ds.getTables().get(0));}return ds;}/*** 执行非查询命令* @param configFilePath* @param commandType* @param commandText* @throws Exception*/public static void executeNonQuery(String configFilePath, CommandType commandType, String commandText) throws Exception {executeNonQuery(configFilePath, commandType, commandText, new Parameter[0]);}/*** 执行非查询命令,带参数* @param configFilePath* @param commandType* @param commandText* @param parameters* @throws Exception*/public static void executeNonQuery(String configFilePath, CommandType commandType, String commandText, Parameter... parameters) throws Exception {try (Connection conn = getConnection(configFilePath)) {executeNonQuery(conn, commandType, commandText, parameters);}}/*** 执行非查询命令* @param connection* @param commandType* @param commandText* @throws Exception*/public static void executeNonQuery(Connection connection, CommandType commandType, String commandText) throws Exception {executeNonQuery(connection, commandType, commandText, new Parameter[0]);}/*** 执行非查询命令,带参数* @param connection* @param commandType* @param commandText* @param parameters* @throws Exception*/public static void executeNonQuery(Connection connection, CommandType commandType, String commandText, Parameter... parameters) throws Exception {if (commandType == CommandType.TEXT) {try (PreparedStatement pstmt = connection.prepareStatement(commandText)) {// 设置参数for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];if (p.direction == ParameterDirection.IN) {pstmt.setObject(i + 1, p.value, p.type);}}// 执行更新pstmt.executeUpdate();}} else if (commandType == CommandType.STORE_PROCEDURE) {StringBuilder paramPlaceholders = new StringBuilder();for (int i = 0; i < parameters.length; i++) {paramPlaceholders.append("?, ");}if (paramPlaceholders.length() > 0) {paramPlaceholders = new StringBuilder(" ( " + paramPlaceholders.substring(0, paramPlaceholders.length() - 2) + " ) ");}String sql = "{ call " + commandText + paramPlaceholders + " }";try (CallableStatement proc = connection.prepareCall(sql)) {// 设置参数for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];if (p.direction == ParameterDirection.IN) {proc.setObject(i + 1, p.value, p.type);} else if (p.direction == ParameterDirection.OUT) {proc.registerOutParameter(i + 1, p.type);}}// 执行存储过程proc.execute();// 处理输出参数for (int i = 0; i < parameters.length; i++) {Parameter p = parameters[i];if (p.direction == ParameterDirection.OUT) {p.value = proc.getObject(i + 1);}}}} else {throw new IllegalArgumentException("不支持的命令类型: " + commandType);}}/*** 将ResultSet转换为DataTable* @param rs* @return* @throws Exception*/private static DataTable convertResultSetToDataTable(ResultSet rs) throws Exception {ResultSetMetaData rsmd = rs.getMetaData();int columnCount = rsmd.getColumnCount();DataTable dt = new DataTable();while (rs.next()) {DataRow dr = new DataRow();for (int i = 1; i <= columnCount; i++) {DataColumn dc = new DataColumn(rsmd.getColumnName(i), rs.getObject(i));dr.addColumn(dc);}dt.addRow(dr);}return dt;}
}
/**** @param schoolId* @return DataSet*/@Overridepublic DuOracleHelper.DataSet getSchoolByDataSet(String schoolId) {String sql = "SELECT * FROM School WHERE SchoolId = ?";try {// 示例1:执行SQL查询DuOracleHelper.DataSet resultSet = DuOracleHelper.executeDataSet("oraclecon.json",DuOracleHelper.CommandType.TEXT,sql,new DuOracleHelper.Parameter(schoolId, DuOracleHelper.ParameterDirection.IN, Types.VARCHAR));return resultSet;}catch (Exception e) {e.printStackTrace();return null;}}

调用:

 DuOracleHelper.DataSet resultSet =schoolBLL.getSchoolByDataSet("U0040");System.out.println(resultSet.toString());

项目结构:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/89087.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/89087.shtml
英文地址,请注明出处:http://en.pswp.cn/pingmian/89087.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OSPFv3-一二类LSA

文章目录OSPFv3 LSA类型Router LSANetwork LSA&#x1f3e1;作者主页&#xff1a;点击&#xff01; &#x1f916;Datacom专栏&#xff1a;点击&#xff01; ⏰️创作时间&#xff1a;2025年07月12日20点01分 OSPFv3 LSA类型 Router LSA 不再包含地址信息&#xff0c;使能 OS…

HugeGraph 【图数据库】JAVA调用SDK

1.引入依赖<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.0-jre</version> </dependency><dependency><groupId>com.squareup.okhttp3</groupId><artifac…

软考中级【网络工程师】第6版教材 第2章 数据通信基础(中)

考点分析&#xff1a;重要程度&#xff1a;⭐⭐⭐&#xff0c;本章可能是全书最难的章节&#xff0c;偏理论&#xff0c;公式多除了传输介质&#xff0c;其他知识点只考选择题&#xff0c;考试一般占3 ~ 5分高频考点&#xff1a;PCM、奈奎斯特定理、曼彻斯特编码&#xff1b;难…

单片机(STM32-中断)

一、中断基础知识 1.概念 中断&#xff08;Interrupt&#xff09;是一种特殊的事件处理机制。当CPU正在执行主程序时&#xff0c;如果出现了某些紧急或重要的事件&#xff08;如外设请求、定时器溢出等&#xff09;&#xff0c;可以暂时中止当前的程序&#xff0c;转而去处理…

gitlab-ci.yml

.gitlab-ci.yml 文件的位置 该文件应放置在 GitLab 项目的代码仓库的根目录 下&#xff0c;具体说明如下&#xff1a;存储库根目录 .gitlab-ci.yml 是 GitLab 持续集成&#xff08;CI&#xff09;的配置文件&#xff0c;需直接放在项目的代码仓库的根目录&#xff08;与 .git 目…

使用JS编写一个购物车界面

使用JS编写一个购物车界面 今天我们来剖析一个精心设计的家具商店购物车页面&#xff0c;这个页面不仅美观大方&#xff0c;还具备丰富的交互功能。让我们一步步拆解它的设计理念和技术实现&#xff01; 页面展示 页面整体结构 这个购物车页面采用了经典的电商布局模式&…

零信任安全架构:如何在云环境中重构网络边界?

一、云原生时代&#xff1a;传统防火墙为何轰然倒塌&#xff1f; 当业务碎片化散落在AWS、阿里云、私有IDC&#xff0c;当员工随手在咖啡厅WiFi连接生产数据库&#xff0c;“内网可信”的基石瞬间崩塌&#xff0c;传统防火墙彻底沦为马奇诺防线&#xff1a; 边界消亡&#xff1…

css实现烧香效果

效果&#xff1a;代码&#xff1a;<!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>动态香烛效果&…

硬件产品的技术资料管控是确保研发可追溯、生产可复制、质量可控制的核心环节。

硬件产品的技术资料管控是确保研发可追溯、生产可复制、质量可控制的核心环节。以下针对BOM单、PCB文件、程序代码、原理图四大核心要素&#xff0c;结合行业实践提出管控方向划分及优化策略&#xff1a;&#x1f4cb; 一、硬件BOM单的精细化管控方向BOM单是硬件生产的“配方表…

Uniswap V2/V3/V4简短说明

Uniswap 是以太坊上最知名的去中心化交易所&#xff08;DEX&#xff09;&#xff0c;它通过不同的版本&#xff08;V2、V3、V4&#xff09;不断改进&#xff0c;变得更高效、更灵活。以下是用通俗易懂的方式介绍它们之间的异同&#xff1a; Uniswap V2&#xff1a;基础版&#…

C++面向对象创建打印算术表达式树

C面向对象&#xff0c;实现算术表达式树的创建和打印的案例&#xff0c;来源于《C沉思录》第八章&#xff0c;涉及数据抽象、继承、多态&#xff08;动态绑定&#xff09;、句柄&#xff0c;其中句柄的使用是核心&#xff0c;关于句柄的较为简单的文章链接点击这里&#xff0c;…

力扣每日一题--2025.7.16

&#x1f4da; 力扣每日一题–2025.7.16 &#x1f4da; 3201. 找出有效子序列的最大长度 I&#xff08;中等&#xff09; 今天我们要解决的是力扣上的第 3201 题——找出有效子序列的最大长度 I。这道题虽然标记为中等难度&#xff0c;但只要掌握了正确的思路&#xff0c;就能…

SFT:大型语言模型专业化定制的核心技术体系——原理、创新与应用全景

本文由「大千AI助手」原创发布&#xff0c;专注用真话讲AI&#xff0c;回归技术本质。拒绝神话或妖魔化。搜索「大千AI助手」关注我&#xff0c;一起撕掉过度包装&#xff0c;学习真实的AI技术&#xff01; 以下基于权威期刊、会议论文及技术报告&#xff0c;对监督微调&#x…

若依前后端分离框架配置多数据库表

若依前后端分离框架配置多数据库表1、配置application.yml2、注释掉application-druid.yml中的数据库3、在DataSourceType 中添加新增的数据库来源4、配置DruidConfig文件4、1新增注入方法&#xff0c;在DataSourceType类添加数据源枚举4、2在DruidConfig类dataSource方法添加数…

29.安卓逆向2-frida hook技术-逆向os文件(二)IDA工具下载和使用(利用ai分析so代码)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 内容参考于&#xff1a;图灵Python学院 工具下载&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1bb8NhJc9eTuLzQr39lF55Q?pwdzy89 提取码&#xff1…

[析]Deep reinforcement learning for drone navigation using sensor data

Deep reinforcement learning for drone navigation using sensor data 基于传感器数据的无人机导航深度强化学习方法 评价&#xff1a;MDP无记忆性&#xff0c;使用LSTM补足缺点。PPO解决新旧策略差距大的问题。 对于环境中的障碍物&#xff0c;设置增量课程&#xff0c;障碍…

SpringBoot项目启动报:java: 找不到符号 符号: 变量 log 的解决办法

问题&#xff1a;使用IDEA创建SpringBoot项目&#xff0c;在项目中使用 Slf4j 注解引入log日志后&#xff0c;启动项目&#xff0c;报如下错误&#xff1a;原因&#xff1a;网上找了很多博文&#xff0c;说是lombook依赖没有引入&#xff0c;但是我的pom.xml中已经引入 lombook…

HTML基础知识 二(创建容器和表格)

HTML 基础知识&#xff1a;创建容器和表格&#xff08;补充版&#xff09;HTML&#xff08;超文本标记语言&#xff09;是构建网页的基础。容器元素用于组织内容&#xff0c;表格用于展示结构化数据&#xff0c;两者都是网页设计中不可或缺的部分。一、HTML 容器元素容器元素就…

多目标优化|HKELM混合核极限学习机+NSGAII算法工艺参数优化、工程设计优化,四目标(最大化输出y1、最小化输出y2,y3,y4),Matlab完整源码

基本介绍 1.HKELM混合核极限学习机NSGAII多目标优化算法&#xff0c;工艺参数优化、工程设计优化&#xff01;&#xff08;Matlab完整源码和数据&#xff09; 多目标优化是指在优化问题中同时考虑多个目标的优化过程。在多目标优化中&#xff0c;通常存在多个冲突的目标&#x…

【AI智能体】Dify 基于知识库搭建智能客服问答应用详解

目录 一、前言 二、Dify 介绍 2.1 Dify 核心特点 三、AI智能体构建智能客服系统介绍 3.1 基于AI智能体平台搭建智能客服系统流程 3.1.1 需求分析与场景设计 3.1.2 选择合适的AI智能体平台 3.1.3 工作流编排与调试 3.1.4 系统集成与发布 3.2 使用AI智能体构建智能客服系…