2013-10-08 86 views
0

我想使用PreparedStatement的,我使用的Oracle數據庫中創建自動遞增的ID,這是我的代碼創建的PreparedStatement自動增量ID

public Client newClient(Client client){ 
     try { 
      con = DBConnection.getConnection(driver, url, name, pass);  
      pstmt = con.prepareStatement("INSERT INTO CLIENT (FIRSTNAME, LASTNAME, CAREER, CSALARY) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); 
      pstmt.setString(1, client.getFirstName()); 
      pstmt.setString(2, client.getLastName()); 
      pstmt.setString(3, client.getCareer()); 
      pstmt.setInt(4, client.getcSalary()); 
      pstmt.executeUpdate();  
      rs = pstmt.getGeneratedKeys(); 
      rs.next(); 

      int id = rs.getInt(1); 
      client.setcId(id); 
    }catch(Exception ex){ 
     ex.printStackTrace(); 
     return null; 
    }finally{ 
     try{ rs.close(); }catch (Exception e){} 
     try{ pstmt.close();}catch (Exception e){} 
     try{ con.close();}catch (Exception e){} 
    }//finally 
    return client; 
}` 

,但我有這個錯誤

java.sql.SQLException: ORA-01400: cannot insert NULL into ("AHMAD"."CLIENT"."CID") 

PLZ幫我

+1

AFAIK,Oracle沒有任何稱爲auto_increment的東西。如果您使用的是序列,則必須明確地將sequence.nextval設置爲該鍵,否則使用觸發器更新該列。 –

+0

您需要創建一個觸發器來處理自動ID生成。 –

+0

非常感謝你的答覆,但你可以給我舉例cuz我嘗試使用seq.nextval,但我有相同的錯誤 – Ahmad

回答

2

聽起來像是你需要一個autonumber sequence

要按序列順序檢索下一個值,您需要使用nextval的 。

例如:

supplier_seq.nextval

,這將您INSERT提供自動遞增序列ID(即您只需執行INSERT和DB將插入自動增量值)