- //方法一
- //采用pl/sql的returning into语法,可以用CallableStatement对象设置registerOutParameter取得输出变量的值。
- //这种方法的优点是只要一次sql交互,性能较好,缺点是需要采用pl/sql语法,代码不直观,使用较少。
- public int insertDataReturnKeyByPlsql() throws Exception {
- Connection conn = getConnection();
- String vsql = "begin insert into t1(id) values(seq_t1.nextval) returning id into :1;end;";
- CallableStatement cstmt =(CallableStatement)conn.prepareCall ( vsql);
- cstmt.registerOutParameter(1, Types.BIGINT);
- cstmt.execute();
- int id=cstmt.getInt(1);
- System.out.print("id:"+id);
- cstmt.close();
- return id;
- }
- //方法二
- //采用PreparedStatement的getGeneratedKeys方法
- //conn.prepareStatement的第二个参数可以设置GeneratedKeys的字段名列表,变量类型是一个字符串数组
- //注:对Oracle数据库这里不能像其它数据库那样用prepareStatement(vsql,Statement.RETURN_GENERATED_KEYS)方法,这种语法是用来取自增类型的数据。
- //Oracle没有自增类型,全部采用的是sequence实现,如果传Statement.RETURN_GENERATED_KEYS则返回的是新插入记录的ROWID,并不是我们相要的sequence值。
- //这种方法的优点是性能良好,只要一次sql交互,实际上内部也是将sql转换成oracle的returning into的语法,缺点是只有Oracle10g才支持,使用较少。
- public int insertDataReturnKeyByGeneratedKeys() throws Exception {
- Connection conn = getConnection();
- String vsql = "insert into t1(id) values(seq_t1.nextval)";
- PreparedStatement pstmt =(PreparedStatement)conn.prepareStatement(vsql,new String[]{"ID"});
- pstmt.executeUpdate();
- ResultSet rs=pstmt.getGeneratedKeys();
- rs.next();
- int id=rs.getInt(1);
- rs.close();
- pstmt.close();
- System.out.print("id:"+id);
- return id;
- }
- //方法三
- //和方法一类似,采用oracle特有的returning into语法,设置输出参数,但是不同的地方是采用OraclePreparedStatement对象,因为jdbc规范里标准的PreparedStatement对象是不能设置输出类型参数。
- //最后用getReturnResultSet取到新插入的sequence值,
- //这种方法的优点是性能最好,因为只要一次sql交互,oracle9i也支持,缺点是只能使用Oracle jdbc特有的OraclePreparedStatement对象。
- public int insertDataReturnKeyByReturnInto() throws Exception {
- Connection conn = getConnection();
- String vsql = "insert into t1(id) values(seq_t1.nextval) returning id into :1";
- OraclePreparedStatement pstmt =(OraclePreparedStatement)conn.prepareStatement(vsql);
- pstmt.registerReturnParameter(1, Types.BIGINT);
- pstmt.executeUpdate();
- ResultSet rs=pstmt.getReturnResultSet();
- rs.next();
- int id=rs.getInt(1);
- rs.close();
- pstmt.close();
- System.out.print("id:"+id);
- return id;
- }
三种最有效的操作Oracle Sequence的方法
最新推荐文章于 2023-10-31 18:51:33 发布