mysql、oracle的JDBC操作

java 复制代码
package com.catarc.paramanalysis.util;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.*;
import java.util.*;
import javax.sql.DataSource;

/**
 * MySQL JDBC 工具类
 * 功能:连接管理、CRUD操作、事务控制、连接池
 */
public class MySQLUtils {
    // 连接池数据源
    private static DataSource dataSource;

    // 初始化连接池
    static {
        try {
            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
            ds.setUrl("jdbc:mysql://888.88.888.888:4417/param_analysis?useSSL=false&serverTimezone=UTC");
            ds.setUsername("888");
            ds.setPassword("888888");
            ds.setInitialSize(5);      // 初始连接数
            ds.setMaxTotal(20);        // 最大连接数
            ds.setMaxIdle(10);         // 最大空闲连接
            ds.setMinIdle(5);          // 最小空闲连接
            ds.setMaxWaitMillis(5000); // 获取连接最大等待时间(毫秒)
            dataSource = ds;
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化连接池失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行查询(返回List<Map>)
     */
    public static List<Map<String, Object>> queryForList(String sql, Object... params) {
        List<Map<String, Object>> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            rs = pstmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {
                Map<String, Object> row = new LinkedHashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnLabel(i), rs.getObject(i));
                }
                list.add(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, rs);
        }
        return list;
    }

    /**
     * 执行查询(返回单个Map)
     */
    public static Map<String, Object> queryForMap(String sql, Object... params) {
        List<Map<String, Object>> list = queryForList(sql, params);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 执行更新(INSERT/UPDATE/DELETE)
     */
    public static int update(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }
        return result;
    }

    /**
     * 批量更新
     */
    public static int[] batchUpdate(String sql, List<Object[]> paramsList) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int[] result = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for (Object[] params : paramsList) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
                pstmt.addBatch();
            }

            result = pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }
        return result;
    }

    /**
     * 执行事务
     */
    public static boolean executeTransaction(TransactionCallback callback) {
        Connection conn = null;
        boolean result = false;

        try {
            conn = getConnection();
            conn.setAutoCommit(false);

            // 执行回调
            result = callback.doInTransaction(conn);

            if (result) {
                conn.commit();
            } else {
                conn.rollback();
            }
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            close(conn, null, null);
        }
        return result;
    }

    /**
     * 事务回调接口
     */
    public interface TransactionCallback {
        boolean doInTransaction(Connection conn) throws SQLException;
    }
}

这样用

List<Map<String, Object>> batch = MySQLUtils.queryForList(sql, currentId,endId, batchSize);

java 复制代码
package com.catarc.paramanalysis.util;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Oracle JDBC 工具类
 * 功能:连接管理、CRUD操作、事务控制、连接池
 */
@Component
public class OracleUtils implements ApplicationListener<ContextRefreshedEvent> {
    // 连接池数据源(静态字段,全局唯一)
    private static DataSource dataSource;

    // 配置参数(实例字段,通过@Value注入)
    @Value("${oracle.driverClassName}")
    private String driverClassName;
    @Value("${oracle.url}")
    private String url;
    @Value("${oracle.username}")
    private String username;
    @Value("${oracle.password}")
    private String password;
    @Value("${oracle.defaultSchema:}")
    private String defaultSchema;

    // 监听Spring上下文初始化完成事件
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 确保只初始化一次(避免父子容器重复触发)
        if (dataSource == null) {
            try {
                BasicDataSource ds = new BasicDataSource();
                ds.setDriverClassName(driverClassName);
                ds.setUrl(url);
                ds.setUsername(username);
                ds.setPassword(password);

                // 连接池配置
                ds.setInitialSize(5);
                ds.setMaxTotal(20);
                ds.setMaxIdle(10);
                ds.setMinIdle(5);
                ds.setMaxWaitMillis(5000);

                // 设置默认Schema(非必需)
                if (defaultSchema != null && !defaultSchema.isEmpty()) {
                    ds.setDefaultSchema(defaultSchema);
                }

                // 验证连接有效性
                ds.setTestOnBorrow(true);
                ds.setValidationQuery("SELECT 1 FROM DUAL");

                dataSource = ds;
                System.out.println("Oracle连接池初始化成功");
            } catch (Exception e) {
                throw new RuntimeException("初始化Oracle连接池失败: " + e.getMessage(), e);
            }
        }
    }

    /**
     * 获取数据库连接(直接访问静态dataSource)
     */
    public static Connection getConnection() throws SQLException {
        if (dataSource == null) { // 检查数据源是否已初始化
            throw new SQLException("Oracle连接池未初始化,请检查Spring配置或上下文是否加载完成");
        }
        return dataSource.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close(); // 连接池环境下实际是归还连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行查询(返回List<Map>)
     */
    public static List<Map<String, Object>> queryForList(String sql, Object... params) {
        List<Map<String, Object>> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            // 设置参数(Oracle参数索引从1开始)
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            rs = pstmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {
                Map<String, Object> row = new LinkedHashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnLabel(i), rs.getObject(i));
                }
                list.add(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, rs);
        }
        return list;
    }

    /**
     * 执行查询(返回单个Map)
     */
    public static Map<String, Object> queryForMap(String sql, Object... params) {
        List<Map<String, Object>> list = queryForList(sql, params);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 执行更新(INSERT/UPDATE/DELETE)
     */
    public static int update(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }
        return result;
    }

    /**
     * 批量更新
     */
    public static int[] batchUpdate(String sql, List<Object[]> paramsList) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int[] result = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            for (Object[] params : paramsList) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
                pstmt.addBatch();
            }

            result = pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, pstmt, null);
        }
        return result;
    }

    /**
     * 执行事务
     */
    public static boolean executeTransaction(TransactionCallback callback) {
        Connection conn = null;
        boolean result = false;

        try {
            conn = getConnection();
            conn.setAutoCommit(false); // 关闭自动提交,开启事务

            result = callback.doInTransaction(conn);

            if (result) {
                conn.commit();
            } else {
                conn.rollback();
            }
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            close(conn, null, null);
        }
        return result;
    }

    /**
     * 事务回调接口
     */
    public interface TransactionCallback {
        boolean doInTransaction(Connection conn) throws SQLException;
    }
}

这样用

List<Map<String, Object>> maps = OracleUtils.queryForList("select * from job_zj_statisticalnumber where staticnumber = ?", after.getStaticNumber());

相关推荐
程序员小八7773 分钟前
MySQL 事务:一文把 ACID、隔离级别、MVCC、锁全串起来
数据库·mysql
lzhdim20 分钟前
提高 SQL 语句执行速度的方法
java·开发语言·数据库·sql·oracle
ltl1 小时前
ClickHouse Distributed 引擎与分布式查询路由
数据库
Wang's Blog1 小时前
PostgreSQL笔记60: 权限与角色管理——从层级体系到最佳实践
数据库·笔记·postgresql
whcyhhh2 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
Elastic 中国社区官方博客3 小时前
让大模型思考,让小模型执行:在 Elastic Workflows 中拆分 LLM 成本
大数据·运维·数据库·人工智能·elasticsearch·ai
Faith_xzc3 小时前
一条 SQL 顶一条 Flink 链路?Doris Streaming Job 持续导入全景解析
大数据·数据库·sql·flink
阮胜昌4 小时前
MySQL 中的动态数据脱敏:无需更改应用程序即可保护敏感数据
android·mysql·adb
小白说大模型6 小时前
AI驱动的个性化学习路径:知识图谱与知识点关联的存储与推理
大数据·人工智能·学习·mysql·机器学习·prompt·知识图谱
这个DBA有点耶6 小时前
多模数据库深度解读:从“多库拼装”到“一库多能”的架构演进
数据库·mysql·dba