Ahmad
Ahmad

Reputation: 91

create auto increment id in preparedstatement

i want to create auto increment id using preparedstatement, i'm using oracle database and this is my code

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;
}`   

but i have this error

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

plz help me

Upvotes: 0

Views: 1779

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272227

Sounds like you need an autonumber sequence

To retrieve the next value in the sequence order, you need to use nextval.

For example:

supplier_seq.nextval

and that will provide an autoincremented sequence id for your INSERT (i.e. you simply perform the INSERT and the db will insert the autoincremented value)

Upvotes: 2

Related Questions