Java 如何在不使用seq.currval的情况下检索序列的当前ID
我需要最后一个id,在java中插入到persons中进行一些操作。 我有两个insert,如果我使用getGeneratedKeys,我会得到“不允许操作”错误。我使用select查询来检索序列的当前值,但它会导致“预期出现into子句”错误。我如何才能访问最后一个人id。 查询:Java 如何在不使用seq.currval的情况下检索序列的当前ID,java,sql,database,oracle,Java,Sql,Database,Oracle,我需要最后一个id,在java中插入到persons中进行一些操作。 我有两个insert,如果我使用getGeneratedKeys,我会得到“不允许操作”错误。我使用select查询来检索序列的当前值,但它会导致“预期出现into子句”错误。我如何才能访问最后一个人id。 查询: begin insert into Persons (Id,First_Name,Last_Name) values (person_se
begin
insert into Persons
(Id,First_Name,Last_Name)
values (person_seq.nextval ,? ,? );
insert into Relations (relation_id, person_id)
values (relation_seq.nextval,person_seq.currval);
SELECT person_seq.currval FROM DUAL;
end;
java代码:
stmt = connectionManager.getConnection().prepareStatement(query);//,new String[] {"ID"});
stmt.setString(1, family.getFName());
stmt.setString(2, family.getLName());
ResultSet resultSet = stmt.executeQuery();
ret = resultSet.getLong(1);
您可以通过RETURNING INTO子句声明一个变量来存储新id:
declare
new_id number; --or your id row type
begin
insert into Persons
(Id,First_Name,Last_Name)
values (person_seq.nextval ,? ,? )
returning id into new_id;
insert into Relations (relation_id, person_id)
values (relation_seq.nextval,person_seq.currval);
end;
此查询中可能存在重复的i have 2 insert。然后我不能使用生成的密钥,当我使用返回时,我得到了错误,我无法获取它返回的内容。谢谢您的回答。如何在java代码中访问新的\u id我使用executeQuery并获取错误“无法对PLSQL语句执行获取:下一步”我已经有一段时间没有使用java了,但看看这个答案是否对您有帮助: