Java数据库交互实战:JDBC核心技术与事务管理精解(附SQL联动案例)

一、JDBC基础操作流程
// 1. 驱动加载与连接建立
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection conn = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/testdb", 
        "user", 
        "password")) {
    
    // 2. 预编译声明对象
    String sql = "SELECT * FROM employees WHERE dept_id = ?";
    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setInt(1, 101);  // 参数绑定

        // 3. 结果集处理
        try (ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                System.out.println(rs.getString("emp_name") 
                    + " | " + rs.getDouble("salary"));
            }
        }
    }
}

二、事务管理关键代码
try (Connection conn = dataSource.getConnection()) {
    conn.setAutoCommit(false);  // 关闭自动提交
    
    try {
        // 转账操作示例
        updateBalance(conn, "A001", -500.0);  // 转出
        updateBalance(conn, "B002", +500.0);  // 转入
        
        conn.commit();  // 提交事务
    } catch (SQLException e) {
        conn.rollback();  // 回滚事务
        System.err.println("事务回滚: " + e.getMessage());
    }
}

// 更新账户方法
private void updateBalance(Connection conn, String accId, double amount) 
        throws SQLException {
    String sql = "UPDATE accounts SET balance = balance + ? WHERE account_id = ?";
    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setDouble(1, amount);
        pstmt.setString(2, accId);
        pstmt.executeUpdate();
    }
}

三、SQL与Java联动解析

场景:多表关联查询

/* SQL语句 */
SELECT o.order_id, c.cust_name, p.product_name
FROM orders o
JOIN customers c ON o.cust_id = c.cust_id
JOIN products p ON o.product_id = p.product_id
WHERE o.order_date > '2023-01-01'

Java映射实现

public class OrderDetail {
    private int orderId;
    private String customerName;
    private String productName;
    
    // 结果集映射构造器
    public OrderDetail(ResultSet rs) throws SQLException {
        this.orderId = rs.getInt("order_id");
        this.customerName = rs.getString("cust_name");
        this.productName = rs.getString("product_name");
    }
    
    // 使用示例
    public static List<OrderDetail> getRecentOrders(Connection conn) {
        List<OrderDetail> list = new ArrayList<>();
        String sql = "/* 上述SQL语句 */";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    list.add(new OrderDetail(rs));
                }
            }
        }
        return list;
    }
}

四、事务隔离级别实践
// 设置读已提交隔离级别
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

// 避免脏读的查询模式
try (Statement stmt = conn.createStatement(
        ResultSet.TYPE_SCROLL_INSENSITIVE, 
        ResultSet.CONCUR_READ_ONLY)) {
    
    ResultSet rs = stmt.executeQuery("SELECT * FROM inventory");
    while (rs.next()) {
        // 保证读取已提交数据
    }
}

五、连接池最佳实践
// HikariCP配置示例
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost/testdb");
config.setUsername("user");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");

try (HikariDataSource ds = new HikariDataSource(config);
     Connection conn = ds.getConnection()) {
     
    // 执行数据库操作
}

核心要点总结

  1. 使用PreparedStatement防止SQL注入
  2. 事务操作遵循ACID原则:
    • 原子性(Atomicity)
    • 一致性(Consistency)
    • 隔离性(Isolation)
    • 持久性(Durability)
  3. 连接池配置参数需根据业务负载调整
  4. 结果集处理推荐使用try-with-resources自动关闭资源
  5. 隔离级别选择需平衡数据一致性与系统吞吐量

通过以上代码示例和解析,可系统掌握Java数据库交互的核心技术要点,实际开发中应根据具体业务场景优化实现方案。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐