zoukankan      html  css  js  c++  java
  • 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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    pig安装
    [2013.10.29][Luogu OJ P1873]砍树
    [转帖]OIer之魂、
    [转帖]我们是OIer、
    10007:[2013.10.25]P1.滚土豆(potato.pas/c/cpp)
    [2013.10.18]P2.传作业 (pass.pas/c/cpp)
    [Luogu OJ P1619]解一元二次方程的烦恼
    [Luogu OJ P1433][2013.10.18]DFS基础题-吃奶酪
    高精度加减乘法小程序 Ver 0.9.5 beta
    [2013.10.11]P3.和为零
  • 原文地址:https://www.cnblogs.com/roadlandscape/p/12190106.html
Copyright © 2011-2022 走看看