JDBC使用事务实例
时间:2021-07-01 10:21:17
帮助过:2人阅读
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使用事务实例
标签: