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());

相关推荐
IvorySQL3 小时前
PostgreSQL 分区表的 ALTER TABLE 语句执行机制解析
数据库·postgresql·开源
·云扬·3 小时前
MySQL 8.0 Redo Log 归档与禁用实战指南
android·数据库·mysql
IT邦德3 小时前
Oracle 26ai DataGuard 搭建(RAC到单机)
数据库·oracle
惊讶的猫3 小时前
redis分片集群
数据库·redis·缓存·分片集群·海量数据存储·高并发写
不爱缺氧i4 小时前
完全卸载MariaDB
数据库·mariadb
纤纡.4 小时前
Linux中SQL 从基础到进阶:五大分类详解与表结构操作(ALTER/DROP)全攻略
linux·数据库·sql
jiunian_cn4 小时前
【Redis】渐进式遍历
数据库·redis·缓存
橙露4 小时前
Spring Boot 核心原理:自动配置机制与自定义 Starter 开发
java·数据库·spring boot
冰暮流星4 小时前
sql语言之分组语句group by
java·数据库·sql
符哥20084 小时前
Ubuntu 常用指令集大全(附实操实例)
数据库·ubuntu·postgresql