JDBC控制事务:
事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。 操作: a. 开启事务 b. 提交事务 c. 回滚事务 使用Connection对象来管理事务 a. 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务 b. 在执行sql之前开启事务 c. 提交事务:commit() d. 当所有sql都执行完提交事务 e. 回滚事务:rollback() f. 在catch中回滚事务 代码:
public class JDBCDemo {
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) ;
}
}
}