如何得到JDBCInsert语句执行后插入数据库记录的主键
答案:1 悬赏:0 手机版
解决时间 2021-12-22 12:25
- 提问者网友:戎马万世
- 2021-12-21 16:35
如何得到JDBCInsert语句执行后插入数据库记录的主键
最佳答案
- 五星知识达人网友:冷風如刀
- 2022-01-06 01:36
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);
}
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);
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯