首页 > 数据库技术 > 详细

JDBC管理事务

时间:2020-01-14 09:11:01      阅读:69      评论:0      收藏:0      [点我收藏+]
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();
                }
            }
        }
    }
}

JDBC管理事务

原文:https://www.cnblogs.com/roadlandscape/p/12190106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!