2015-02-10 53 views
0

我需要最后一个id,插入到人员中以便在java中执行一些操作。 我有两个插入,然后如果我使用getGeneratedKeys我得到“操作不允许”的错误。我使用select查询来检索当前的序列值,但它会导致“预期的进入子句”错误。我怎么能设法访问最后一个人的ID。 查询:如何在不使用seq.currval的情况下检索序列的当前标识

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

可能重复[如何获得来自最后插入的行的值?](http://stackoverflow.com/questions/241003/how-to-get-a-value-from-the-last-inserted-row) – user1717259 2015-02-10 16:30:46

+0

我在此查询中有2个插入。那么我不能使用生成的密钥,当我使用返回我有错误,我不能获取它返回。 – user4002899 2015-02-10 17:20:22

回答

2

可以声明一个变量来存储新的ID与返回的INTO子句:

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; 
+0

感谢您的回答。我如何在Java代码中访问new_id我使用executeQuery并获取错误“无法对PLSQL语句执行提取操作:next” – user4002899 2015-02-10 17:15:44

+0

我有一段时间没有使用java,但看看这个答案是否对你有帮助:http:// stackoverflow。 COM /问题/ 1915166 /如何到获得最插入-ID-在-JDBC?LQ = 1 – tilley31 2015-02-10 17:26:19

相关问题