码迷,mamicode.com
首页 > 数据库 > 详细

Java JDBC事务

时间:2019-08-18 15:36:07      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:password   catch   manager   rollback   toc   提交   lex   color   exception   

 

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         }

 

Java JDBC事务

标签:password   catch   manager   rollback   toc   提交   lex   color   exception   

原文地址:https://www.cnblogs.com/chy18883701161/p/11372089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!