如何得到JDBC Insert 语句执行后插入Oracle 数据库记录的主键
在应用中,很多时候会对表的主键用一个自动增涨的数来付值,如Oracle的sequence,插入后又想得到的主键的值。下面介绍一下相关的
在应用中,很多时候会对表的主键用一个自动增涨的数来付值,,如Oracle的sequence,插入后又想得到的主键的值。下面介绍一下相关的方法。
1,用Oracle 的returning 语句。
PreparedStatement sta = conn.prepareStatement("INSERT INTO LOGGING VALUES (TESTSEQ.NEXTVAL,SYSDATE)returning id into ? ");
sta.execute();
ResultSet rset = sta.getResultSet();
while(rset.next())
{
int id = rset.getInt(1);
}
如果是既有传入值,又有返回值的话,应该:
PreparedStatement sta = conn.prepareStatement("BEGIN INSERT INTO LOGGING VALUES
(TESTSEQ.NEXTVAL,? )returning id into ?; END; ");
sta = conn.prepareCall(sqlText);
sta .setString(1, srqID);
sta .registerOutParameter(2, Types.NUMERIC);
sta .execute();
return sta .getLong(2);
或者用oracle的 OraclePreparedStatement
String sql = "insert into test values(1,?) returning id into ?";
OraclePreparedStatement pstt = (OraclePreparedStatement) conn.prepareStatement(sql);
pstt.setString(1, "xxx");
pstt.registerReturnParameter(2, OracleTypes.INTEGER);
pstt.executeUpdate();
ResultSet rset = pstt.getReturnResultSet(); // rest is not null
while (rset.next()) {
int id = rset.getInt(1);
System.out.println("Insert returnning: " + id);
}
2,用JDBC的getGeneratedKeys,返回的是Oracle 的rowid.
PreparedStatement sta = conn.prepareStatement("INSERT INTO TESTTABLE VALUES (TESTSEQ.NEXTVAL,'aaaa')",Statement.RETURN_GENERATED_KEYS);
sta.execute();
System.out.println(sta.getGeneratedKeys());
ResultSet rest = sta.getGeneratedKeys();
rest.next();
//oracle rowid
System.out.println(rest.getString(1));