
在学习JDBC的有关内容后,我们知道可以用它来处理一些事务的问题。那么在具体事务的管理上,需要用到Connection来完成。主要分为三个方面:开启、提交和回滚。下面我们就这些情况,分别进行概念的理解。在掌握了具体的方法后,我们进一步的展开实例代码的学习。
1、管理事务
(1)开启事务setAutoCommit
调用该方法设置参数为false,即开启事务。
在执行sql之前开启事务。
(2)提交事务:commit()
当所有sql都执行完提交事务。
(3)回滚事务:rollback()
在catch中回滚事务。
2、实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | public static void main(String[] args) {
Connection conn = null ;
PreparedStatement pstmt1 = null ;
PreparedStatement pstmt2 = null ;
try {
conn = JDBCUtils.getConnection();
conn.setAutoCommit( false );
String sql1 = "update account set balance = balance - ? where id = ?" ;
String sql2 = "update account set balance = balance + ? where id = ?" ;
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
pstmt1.setDouble(1,500);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,500);
pstmt2.setInt(2,2);
pstmt1.executeUpdate();
int i = 3/0;
pstmt2.executeUpdate();
conn.commit();
} catch (Exception e) {
try {
if (conn != null ) {
conn.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2, null );
}
|
以上就是java中使用Connection管理事务的方法,大家在看懂具体的方法后,可以对代码部分进行运行,对有关操作做到熟练于心。更多Java学习指路:Java基础