JDBC中事务的使用

    当Jdbc程序向数据库获得一个Connection对象时,默认情况下这个Connection对象会自动向数据库提交在它上面发送的SQL语句。若想关闭这种默认提交方式,让多条SQL在一个事务中执行,并且保证这些语句是在同一时间共同执行的时,我们就应该为这多条语句定义一个事务。

    其中,银行转账这一事例,最能说明,使用事务的重要性了。

update from account set money = money - 100 where name = ‘a’;

update from account set money = money + 100 where name = ‘b’;

    因为这时,两个账户的增减变化是在一起执行的。现实生活中这种类似于同步通信的例子还有很多,这里,不再赘述。

    当然,对于事务的编写,也是要遵守一定的顺序的:

    首先,设置事务的提交方式为非自动提交:

conn.setAutoCommit(false);

    接下来,.将需要添加事务的代码放入try,catch块中。

    然后,.在try块内添加事务的提交操作,表示操作无异常,提交事务。

conn.commit();

    尤其不要忘记,.在catch块内添加回滚事务,表示操作出现异常,撤销事务:

conn.rollback();

    最后,设置事务提交方式为自动提交:

conn.setAutoCommit(true);

    这样,通过简单的几步,我们就可以完成对事务处理的编写了。

    例:定义了一个事务方法并在方法内实现了语句之间的一致性操作

Connection con =null;
Statement st=null;
ResultSet rs=null;
PreparedStatement ps=null;
publicvoid startTransaction(){
    con = DBCManager.getConnect();//获取连接对象
    try {
        //设置事务的提交方式为非自动提交:
        con.setAutoCommit(false);
        //将需要添加事务的代码一同放入try,catch块中
        //创建执行语句
        String sql ="delete from me where id = 7";
        String sql1 = "update me set name ='lime' ,age ='24' where id = 4";
        //分别执行事务
        ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps = con.prepareStatement(sql1);
        ps.executeUpdate();
        //在try块内添加事务的提交操作,表示操作无异常,提交事务。
        con.commit();
     } catch (SQLException e) {
        try {
            //.在catch块内添加回滚事务,表示操作出现异常,撤销事务:
            con.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }finally{
        try {
            //设置事务提交方式为自动提交:
            con.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBCManager.release(rs, ps, con);
  }
}            

啦啦啦

posted @ 2017-03-21 17:53  limeOracle  阅读(486)  评论(0编辑  收藏  举报