oracle 事务简介,锁的概念,java访问数据库注意事项

java链接oracle和连接其他数据库一样有两种方式:
1 桥接 jdbc-obdc
2 jbdc

insert语句一次插入大量数据
insert into table (列1,列2,列3) select 列1,列2,列3 from table1;

update语句在更新数据时直接修改数据(oracle特有的)
update table set(列1,列2,列3) = (select 列1,列2,列3, from table1 where.....) where ..... ;

用查询结果创建新表
create table table2 (列1,列2,列3) as select 列11,列22,列33 from table;

oracle中的事务处理
1 锁的概念
2 保存点的使用:
在处理当前事务过程中,还没提交事务时,可以回滚到保存点
savepoint point1;rollback to point1;
提交命令是:commit;
特别指出:每次退出数据库的时候数据库都会自动提交,没有提交相当于内容在变但是没有保存。
3 在java中使用事务
在java中访问数据库时,每执行一条语句就会提交一次,如果多条语句执行过程中,发生错误,会导致表被改变
,并且没按照程序员的意愿发生改变,这时需要利用事务的原理设计程序。

 1 import java.sql.*;
 2 
 3 public class Demo001 {
 4 
 5 public static void main(String[] args) {
 6   Connection ct = null;
 7   try{
 8     Class.forName("oracle.jdbc.driver.OracleDriver");
 9     ct = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:myoracle1","scott","tiger");
11     Statement st = ct.createStatement();
12 
13     //设置ct不自动提交事务
14     ct.setAutoCommit(false);
15 
16     st.executeUpdate("update table set a1 = a1 + 100 where name = 'sss' ");
17 
18     int w = 1/0;//故意制作的异常
19 
20     st.executeUpdate("update table set a2 = a2 - 100 where name = 'sss' ");
21 
22     ct.commit();
23     ct.close();
24     st.close();
25 
26     }catch(Exception e){
27       try {
28         //一旦发生异常则回滚
29         ct.rollback();
30       } catch (SQLException e1) {
31           e1.printStackTrace();
32       }
33     }    
34   }
35 }

 

posted @ 2016-07-21 15:39  小德cyj  阅读(309)  评论(0编辑  收藏  举报