2015-02-10 51 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

相關問題