您的位置:首页 > 数据库 > Oracle

oracle 获取插入 id getGeneratedKeys

2014-02-27 09:51 423 查看
http://blog.csdn.net/xpsharp/article/details/7678028

ORACLE JDBC的getGeneratedKeys

对于JDBC 3.0, 使用statement.getGeneratedKeys()可以返回刚刚插入的记录的自动增长的ID值。对于ORACLE,一般是定义一个序列,然后利用序列的nextval来自动给列分配ID值。但是很多人发现,在利用ORACLE JDBC驱动编写的时候,往往会失败。显示“java.sql.SQLException: Unsupported feature”。

其实,对于ORACLE JDBC,只有在10.2.0.1.0版本后的JDBC才支持getGeneratedKeys特性。而且如果使用下列代码:

String sql = "INSERT INTO FOO (NAME) VALUES ('BAR')";

Statement stmt = connection.createStatement();

stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();

oracle.sql.ROWID rid = (oracle.sql.ROWID) rs.getObject(1); //getLong and getInt fail

// The following fail

// long l = rid.longValue();

// int i = rid.intValue();

String s = rid.stringValue(); // s equals "AAAXcTAAEAAADXYAAB"

返回的将是ROWID值。可以使用下列代码:

String sql = "INSERT INTO ORDERS (ORDER_ID, CUSTOMER_ID) VALUES (ORDER_ID_SEQ.NEXTVAL, ?)";

String generatedColumns[] = {"ORDER_ID"};

PreparedStatement pstmt = conn.prepareStatement(sql, generatedColumns);

pstmt.setLong(1, customerId);

pstmt.executeUpdate();

ResultSet rs = pstmt.getGeneratedKeys();

rs.next();

// The generated order id

long orderId = rs.getLong(1);

能得到正确的ID值。注意,其中generatedColumns[]表示从哪个列来获取新的ID值。我们也可以使用:

int a[]={1};

PreparedStatement pstmt = conn.prepareStatement(sql, a);

......

来表示第1列是KEY列,我们要获取第1列的新插入的值。

目前(20071219)ORACLE JDBC最新的是11g1,推荐使用。http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_11...

另外,Jdeveloper 10.1.3.3里面携带的JDBC驱动也不支持getGeneratedKeys。需要进行更新。

当然,也可以使用第三方的JDBC驱动,如i-net software的Oranxo驱动,支持getGeneratedKeys,而且驱动程序的体积更小。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle getGeneratedK