//这种方法的优点是性能良好,只要一次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;
}
以上5种方法都可以实现功能,以下是5种方法的优缺点汇总,个人推荐性能要求一般的业务采用第一种方法,性能要求非常高业务采用第五种方法。
| 方法 |
简介 |
优点 |
缺点 |
| 方法一 |
先用seq.nextval取出值,然后用转入变量的方式插入 |
代码简单直观,使用的人也最多 |
需要两次sql交互,性能不佳 |
| 方法二 |
先用seq.nextval直接插入记录,再用seq.currval取出新插入的值 |
可以在插入记录后返回sequence,适合于数据插入业务逻辑不好改造的业务代码 |
需要两次sql交互,性能不佳,并且容易产生并发安全问题 |
| 方法三 |
用pl/sql块的returning into语法,用CallableStatement对象设置输出参数取到新插入的值 |
只要一次sql交互,性能较好 |
需要采用pl/sql语法,代码不直观,使用较少 |
| 方法四 |
设置PreparedStatement需要返回新值的字段名,然后用getGeneratedKeys取得新插入的值 |
性能良好,只要一次sql交互 |
只有Oracle10g才支持,使用较少 |
| 方法五 |
returning into语法,用OraclePreparedStatement对象设置输出参数,再用getReturnResultSet取得新增入的值 |
性能最好,因为只要一次sql交互,oracle9i也支持 |
只能使用Oracle jdbc特有的OraclePreparedStatement对象 |
作者:叶正盛
日期:2011-10-30
我的新浪微博:weibo.com/yzsind
