Java操作数据库——在JDBC里使用事务
摘要:本文主要学习了如何在JDBC里使用事务。
使用Connection的事务控制方法
当JDBC程序向数据库获得一个Connection对象时,默认情况下这个Connection对象会自动向数据库提交发送的SQL语句。若想关闭这种默认提交方式,让多条SQL在一个事务中执行,可使用JDBC提供的事务控制方法。
常用方法
查询自动提交的状态:boolean getAutoCommit() throws SQLException;
设置自动提交的状态:void setAutoCommit(boolean autoCommit) throws SQLException;
设置还原点:Savepoint setSavepoint() throws SQLException;
设置指定名称的还原点:Savepoint setSavepoint(String name) throws SQLException;
删除指定名称的还原点:void releaseSavepoint(Savepoint savepoint) throws SQLException;
提交:void commit() throws SQLException;
回滚:void rollback() throws SQLException;
回滚到指定名称的还原点:void rollback(Savepoint savepoint) throws SQLException;
查询隔离级别:int getTransactionIsolation() throws SQLException;
设置隔离级别:void setTransactionIsolation(int level) throws SQLException;
使用实例
1 public static voidmain(String[] args) {2 Properties pros = newProperties();3 try{4 pros.load(TestConnection.class.getClassLoader().getResourceAsStream("jdbc.properties"));5 } catch(IOException e) {6 e.printStackTrace();7 }8 try{9 Class.forName(pros.getProperty("driverClass"));10 } catch(ClassNotFoundException e) {11 e.printStackTrace();12 }13 Connection conn = null;14 PreparedStatement pstmt = null;15 try{16 String url = pros.getProperty("url");17 String user = pros.getProperty("user");18 String password = pros.getProperty("password");19 conn =DriverManager.getConnection(url, user, password);20 boolean status =conn.getAutoCommit();21 System.out.println("AutoCommit = " +status);22 conn.setAutoCommit(false);23 pstmt = conn.prepareStatement("delete from student where id = 906");24 pstmt.executeUpdate();25 int e = 1 / 0;//模拟出现异常
26 pstmt = conn.prepareStatement("delete from student where id = 907");27 pstmt.executeUpdate();28 conn.commit();//手动提交,不能省略
29 } catch(Exception e) {30 e.printStackTrace();31 try{32 conn.rollback();//手动回滚,可以省略,系统会自动回滚
33 } catch(SQLException ex) {34 ex.printStackTrace();35 }36 } finally{37 try{38 pstmt.close();39 } catch(SQLException e) {40 e.printStackTrace();41 }42 try{43 conn.close();44 } catch(SQLException e) {45 e.printStackTrace();46 }47 }48 }