Java操做數據庫——使用JDBC鏈接數據庫

Java操做數據庫——在JDBC裏使用事務

摘要:本文主要學習瞭如何在JDBC裏使用事務。mysql

使用Connection的事務控制方法

當JDBC程序向數據庫得到一個Connection對象時,默認狀況下這個Connection對象會自動向數據庫提交發送的SQL語句。若想關閉這種默認提交方式,讓多條SQL在一個事務中執行,可以使用JDBC提供的事務控制方法。sql

經常使用方法

查詢自動提交的狀態:boolean getAutoCommit() throws SQLException;數據庫

設置自動提交的狀態:void setAutoCommit(boolean autoCommit) throws SQLException;學習

設置還原點:Savepoint setSavepoint() throws SQLException;url

設置指定名稱的還原點:Savepoint setSavepoint(String name) throws SQLException;spa

刪除指定名稱的還原點:void releaseSavepoint(Savepoint savepoint) throws SQLException;code

提交:void commit() throws SQLException;對象

回滾:void rollback() throws SQLException;blog

回滾到指定名稱的還原點: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 }
相關文章
相關標籤/搜索