java-jdbc数据库事务

管理事务:
        开启事务: setAutoCommit( boolean autoCommit) : 调用该方法设置参数为false,即开启事务
        提交事务: commit()
        回滚事务: rollback()

Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
Savepoint savepoint = null;
try {
    //1.获取连接
    conn = JDBCUtils.getConnection();
    //开启事物
    conn.setAutoCommit(false);
    //2.定义sql语句
    String sql1 = "update account set balance = balance - ? where id = ?;";
    String sql2 = "update account set balance = balance + ? where id = ?;";
    //3.获取执行sql对象
    pstmt1 = conn.prepareStatement(sql1);
    pstmt2 = conn.prepareStatement(sql2);
    //4.设置参数
    pstmt1.setInt(1,500);
    pstmt1.setInt(2,1);
    pstmt2.setInt(1,500);
    pstmt2.setInt(2,3);
    //5.执行sql
    pstmt1.executeUpdate();
    pstmt2.executeUpdate();
    //提交事务
    conn.commit();
} catch (Exception e) {
    //事务回滚
    try {
        if(conn != null){
            conn.rollback();
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    e.printStackTrace();
}finally {
    JDBCUtils.close(null , pstmt1 , conn);
    JDBCUtils.close(null , pstmt2,null);
    System.out.println("最后执行");
}

JDBCUtils自定义的jdbc工具类请查看:https://blog.csdn.net/hdsHDS6/article/details/108503723

你可能感兴趣的:(java,数据库,java,mysql,jdbc)