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 void main(String[] args) {
 2     try {
 3         Class.forName("com.mysql.jdbc.Driver");
 4     } catch (ClassNotFoundException e) {
 5         e.printStackTrace();
 6     }
 7     Connection conn = null;
 8     PreparedStatement pstmt = null;
 9     try {
10         String url = "jdbc:mysql://192.168.35.128:3306/demo";
11         String user = "root";
12         String password = "123456";
13         conn = DriverManager.getConnection(url, user, password);
14         boolean status = conn.getAutoCommit();
15         System.out.println("AutoCommit = " + status);
16         conn.setAutoCommit(false);
17         pstmt = conn.prepareStatement("delete from student where id = 906");
18         pstmt.executeUpdate();
19         int e = 1 / 0;// 模拟出现异常
20         pstmt = conn.prepareStatement("delete from student where id = 907");
21         pstmt.executeUpdate();
22         conn.commit();// 手动提交,不能省略
23     } catch (Exception e) {
24         e.printStackTrace();
25         try {
26             conn.rollback();// 手动回滚,可以省略,系统会自动回滚
27         } catch (SQLException ex) {
28             ex.printStackTrace();
29         }
30     } finally {
31         try {
32             pstmt.close();
33         } catch (SQLException e) {
34             e.printStackTrace();
35         }
36         try {
37             conn.close();
38         } catch (SQLException e) {
39             e.printStackTrace();
40         }
41     }
42 }
12-31 14:58