import java.sql.*;
public class TestTransaction { //設置默認提交false即setAutoCommit(false),執(zhí)行完了再commit,try到任何SQLException都要回滾,回滾完了記得將默認提交改回去(true)
public static void main(String[] args) throws SQLException {
Connection conn = null; String url = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL"; Statement stmt = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url, "scott", "lomboz_eclipse"); stmt = conn.createStatement(); conn.setAutoCommit(false); stmt.addBatch("insert into dept values(11,'f','ff')"); stmt.addBatch("insert into dept values(22,'f','ff')"); stmt.addBatch("insert into dept values(32,'f','ff')"); stmt.executeBatch();//注意執(zhí)行在提交前面,不然都提交了還執(zhí)行什么呢 conn.commit(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { try { if(conn !=null) { conn.rollback();//發(fā)生語句異常馬上回滾 conn.setAutoCommit(true);//默認的改回去哦 } } catch (SQLException e1){ e1.printStackTrace(); } e.printStackTrace(); } finally { if(stmt != null) { stmt.close(); stmt = null; } if(conn != null) { conn.close(); conn = null; } } }
}
|