标签:
关于事务:
1、一个事务中的多个操作应该公用一个connection,如果每一个操作都用不同的connection,事务将无法回滚。
2、具体步骤:
1)、在事务开始前,应该取消事务的自动提交,即设置 connection.setAutoCommit(false);
2)、如果事务中的操作都执行成功,则提交事务,即 connection.commit();
3)、如果事务执行过程中出现异常,则在catch中回滚事务,即 connection.rollback();
1 @Test 2 public void testTransaction() throws Exception { 3 Connection connection = null; 4 try{ 5 connection = jdbcTools.getConnection(); 6 System.out.println(connection); 7 connection.setAutoCommit(false); 8 String sql = "update user set balance = balance - 500 where id = 1"; 9 update(connection,sql); 10 11 sql = "update user set balance = balance + 500 where id = 2"; 12 update(connection,sql); 13 14 connection.commit(); 15 16 }catch (Exception e){ 17 e.printStackTrace(); 18 connection.rollback(); 19 }finally { 20 jdbcTools.releaseResource(null,null,connection); 21 } 22 23 24 } 25 26 public void update (Connection connection,String sql){ 27 PreparedStatement preparedStatement = null; 28 try { 29 preparedStatement = connection.prepareStatement(sql); 30 preparedStatement.execute(); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 }finally { 34 jdbcTools.releaseResource(null,preparedStatement,null); 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/hotpoint/p/5479587.html