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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    rapidjson 的练习
    在Struts2中集成Spring详细讲解
    AJAX实例入门
    Redhat Enterprise Linux中如何关闭SELinux?
    C3P0连接池详细配置
    hibernate中load,get;find,iterator;merge,saveOrUpdate,lock的区别
    107个常用Javascript语句
    车祸 shit
    JAVASCRIPT实现XML分页
    javabeans的运用
  • 原文地址:https://www.cnblogs.com/roadlandscape/p/12190106.html
Copyright © 2011-2022 走看看