ORACLE10g及其以上版本 JDBC 获取刚插入一条数据的主键id(转载)

对于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列的新插入的值。

猜你喜欢

转载自jungle323.iteye.com/blog/1639143