我需要在java中插入一些操作的最后一个id。 我有两个插入然后如果我使用getGeneratedKeys我得到“操作不允许”错误。我使用select查询来检索序列的当前值,但它会导致“一个to into子句是预期的”错误。我怎么能设法访问最后一个人的身份证。 查询:
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);
答案 0 :(得分:2)
您可以使用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;