JDBC管理事务

package com.fgy.jdbc;

import java.sql.*;

/**
 * 转账小案例
 */
public class tx {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstm1 = null;
        PreparedStatement pstm2 = null;

        try {
            // 1.导入驱动jar包
            // 2.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 3.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root");
            // 开启事务
            conn.setAutoCommit(false);
            // 4.定义SQL语句
            // fan给li转账500
            String sql1 = "update account set balance = balance - ? where name = ?";
            String sql2 = "update account set balance = balance + ? where name = ?";
            // 5.获取statement对象
            pstm1 = conn.prepareStatement(sql1);
            pstm2 = conn.prepareStatement(sql2);
            pstm1.setDouble(1, 500);
            pstm1.setString(2, "fan");
            pstm2.setDouble(1, 500);
            pstm2.setString(2, "li");
            // 6.执行SQL语句
            pstm1.executeUpdate();
            // 手动制造异常
            // int i = 1 / 0;
            pstm2.executeUpdate();
            // 7.处理结果
            // ....
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            // 8.释放资源
            if (pstm1 != null) {
                try {
                    pstm1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (pstm2 != null) {
                try {
                    pstm1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/roadlandscape/p/12190106.html