JDBC控制事务

Demo11Jdbc
package cn.Dong;

import cn.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*
    事务操作
 */
public class Demo11Jdbc {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement pstmt1=null;
        PreparedStatement pstmt2=null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //2.定义sql
            //2.1   Demo1-100
            String sql1="update bank set acount=acount-? where id=?";
            //2.2  Demo2+100
            String sql2="update bank set acount=acount+? where id=?";
            //3.获取执行sql对象
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            //4设置参数
            pstmt1.setDouble(1,100);
            pstmt1.setInt(2,1);
            //int i=3/0;
            //回滚就会恢复以前状态
            pstmt2.setInt(1,100);
            pstmt2.setInt(2,2);

            //5.执行sql
            pstmt1.executeUpdate();
            pstmt2.executeUpdate();

            //提交事务
            conn.commit();

        } catch (SQLException e) {
            //事务回滚
            try {
                if(conn!=null){
                    conn.rollback();
                }

            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.close(pstmt1,conn);
            JDBCUtils.close(pstmt2,null);

        }
    }
}

你可能感兴趣的:(java)