Java JDBC事務


 

JDBC默認是自動提交,事務是關閉的,statement|preparedStatement.executeUpdate()或excute()執行增刪改,執行一次就提交一次(自動同步到數據庫)。

 

JDBC事務示例:

 1  //從properties文件中加載數據庫配置
 2         Properties properties = new Properties();
 3         InputStream inputStream =Class.forName("test.Test").getResourceAsStream("/mysql.properties");
 4         properties.load(inputStream);
 5 
 6         String driver = properties.getProperty("driver");
 7         String url = properties.getProperty("url");
 8         String user = properties.getProperty("user");
 9         String pwd=properties.getProperty("password");
10 
11         Class.forName(driver);
12         Connection connection = DriverManager.getConnection(url, user, pwd);
13         connection.setAutoCommit(false);   //關閉自動提交,此句代碼會自動開啟事務。默認為true,自動提交。
14 
15         String sql1 = "insert into student_tb (name,age,score) values (?,?,?)";
16         PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
17         preparedStatement1.setString(1,"chy");
18         preparedStatement1.setInt(2,20);
19         preparedStatement1.setInt(3,100);
20         preparedStatement1.executeUpdate();  //放置到隊列中
21 
22         String sql2 = "update student_tb set name=? where id=?";
23         PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
24         preparedStatement2.setString(1,"CoCo");
25         preparedStatement2.setInt(2,10);
26         preparedStatement2.executeUpdate();  //放置到隊列中
27 
28         try{
29             connection.commit();   //提交事務
30         }catch (SQLException e){
31             connection.rollback();  //失敗就回滾
32         } finally {
33             preparedStatement1.close();
34             preparedStatement2.close();
35             connection.close();
36         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM