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

JDBC使用事务实例

时间:2016-05-08 16:55:28      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:

 1 package qddx.JDBC;
 2 import java.sql.*;
 3 public class useTransaction {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Connection conn = null;
 8         Statement st = null;
 9         PreparedStatement pst = null;
10         ResultSet rs = null;
11         Savepoint sp = null;
12         try{
13         conn = JDBC_Connection.getConnection();
14         //指定事务隔离级别
15         conn.setTransactionIsolation(conn.TRANSACTION_READ_UNCOMMITTED);
16         pst = conn.prepareStatement("create table users (id smallint,username text)");
17         pst.execute();
18         //提交事务
19         conn.commit();
20         pst.close();
21         }catch(SQLException e){
22             System.err.println("连接数据库或者建表失败");
23             System.err.println("事务回滚到回滚点");
24             try{
25             conn.rollback();
26             }catch(SQLException ex){
27                 //ex.printStackTrace();
28                 System.out.println("回滚失败");
29             }
30             try{
31             conn.setSavepoint();//设置一个存储点
32             st = conn.createStatement();
33             st.executeUpdate("insert into users values(110,‘Janes‘)");//执行更新语句
34             //st.executeUpdate("insert into users values(‘shibai‘,‘Janes‘)");//执行更新语句 失败的例子
35             conn.commit();//提交事务
36             conn.releaseSavepoint(sp);//释放存储点
37             st.close();
38             conn.close();
39             
40             }catch(SQLException et){
41                 System.err.println("操作失败");
42                 System.err.println("事务回滚到存储点");
43                 try{
44                 conn.rollback(sp);
45                 st.close();
46                 conn.close();
47                 }catch(SQLException exc){
48                     System.out.println("回滚到存储点失败");
49                     //exc.printStackTrace();;
50                 }
51                 //et.printStackTrace();
52             }
53             //e.printStackTrace();
54         }
55         
56     }
57 
58 }

 

JDBC使用事务实例

标签:

原文地址:http://www.cnblogs.com/maple-shanqiu/p/5470827.html

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