day-22-SQL语句-事务-软件分层

来源:互联网 发布:vmware安装mac os x 编辑:程序博客网 时间:2024/06/10 14:21

01.事务_MySQL中的事务处理

一、两种方式:1.关闭自动提交,变成手动提交:    //查看提交状态:        show variables like 'autocommit';    1.关闭自动提交:        set autocommit = off;    2.执行SQL语句:        uptate.....        insert....        delete....    3.提交/回滚        commit;  提交        或者        rollback; 回滚    注意:    1.当提交或者回滚后,之前所有的SQL语句被全部处理,要么全部更改到数据库,要么全部取消。    2.一旦提交后不能再回滚了,一旦被回滚后,就不能再提交了。2.在自动提交的状态下,临时开启一个手动事务:    1.start transaction;//告诉MySQL,我之后做的所有SQL语句先做一个事务给缓存起来;    2.执行SQL语句:        uptate.....        insert....        delete....    3.提交/回滚        commit;        或者        rollback;

02.事务_JDBC中的事务处理

public static void main(String[] args) throws Exception {    //1.注册驱动    Class.forName("com.mysql.jdbc.Driver");    //2.获取连接对象    Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/text01","root","123456");    //关闭自动提交    conn.setAutoCommit(false);    //3.获取SQL值    Statement stmt=conn.createStatement();try{    String sql1="delete from p where id=3";    int row1= stmt.executeUpdate(sql1);    String sql2="delete from p where id=4";    int row2=stmt.executeUpdate(sql2);    System.out.println("结果:"+row1+"   "+row2);    if(row1 !=1 || row2 !=1){        //只要有一条SQL语句返回的不是1,立即回滚        conn.rollback();    }else{        conn.commit();    }}catch(Exception e){    //只要出异常,立即回滚        conn.rollback();    }    stmt.close();    conn.close();}

03.DBUtils的事务处理

public static void main(String[] args) throws Exception {    //1.创建一个QueryRunner对象    QueryRunner qr=new QueryRunner();    //2.准备一个Connection 对象    ComboPooledDataSource ds=new ComboPooledDataSource();    Connection conn=ds.getConnection();    //自动变手动    conn.setAutoCommit(false);    //3.执行SQL    String sql1="update p set money=money+1000 where name='lisi'";    String sql2="update p set money=money-1000 where name='zhangsan'";    try{        //update 调用两个参数        int row1=qr.update(conn,sql1);        int row2=qr.update(conn,sql2);        System.out.println("结果:"+row1+"   "+row2);        if(row1 !=1 || row2 !=1){            //回滚            System.out.println("出错了!!!!!");            conn.rollback();        }else{            //提交            System.out.println("正确!!!");            conn.commit();        }    }catch(Exception e){        //回滚        System.out.println("异常了!!!!");        conn.rollback();    }    //归还连接    conn.setAutoCommit(true);    conn.close();}

04.软件分层

1.在“企业级开发”中,我门一般将代码分为五层;    1.视图层:负责接收数据、命令、展示数据;    2.控制层:负责接收视图层的数据、命令,寻找相应的“业务层”进行处理(业务分发);    3.业务层:负责具体的业务逻辑实现;    4.持久层:负责访问数据库;    5.模型层:负责封装数据,在各层之间传递。2.分层的好处:    将代码解耦,使各功能部分的代码之间的耦合度降到最低,不同功能的代码分到不同的类中存储,后期需要修改时,修改那部分就找那部分的类即可,其他类不用改。
原创粉丝点击