Retrieve primary key after inserting
Retrieve primary key after inserting
От:
Alex Dovlecel <dovle@kbs.twi.tudelft.nl>
Дата:
Hello all, Is there a special mechanism to retrieve the primary key from a record that I just inserted? For example, I have a table with the PK of SERIAL type. So when inserting I let the psql to choose the primary key. But how can I get the primary key that was set for the record? BEcause i have a relation based on that primary key... !!! (I think it is a classic problem...) Does psql have some special feature to help me overcome this problem ? Tx dovle
Re: Retrieve primary key after inserting
От:
"Hale Pringle" <halepringle@yahoo.com>
Дата:
One way to do this is as follows for table "recipients" and id "entryid"
The serial keyword in CREATE TABLE will create a sequence called
"recipients_entryid_seq"
(e.g. "{tableName}_{serialFieldName}_seq"). The nextval() function will
bump the value by one and return the updated value.
private int locID;
public int getID(){
return locID;
}
public void InsertTable(String fields, String values) {
try {
statement =
dbc.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = statement.executeQuery("SELECT
nextval('recipients_entryid_seq')");
while ( rs.next() ) {
locId = rs.getInt("nextval" );
// System.out.println("locId = "+locId);
}
query = "Insert into recipients (entryid,"+fields+ ") values
("+locId+","+values+")";
statement.executeUpdate( query );
//System.out.println( "Recipients Insert Successful new id
= "+locId+" \n" );
}//End try
catch( etc. )
}
>Hello all,
>Is there a special mechanism to retrieve the primary key from a record that
I
>just inserted?
>Tx
>dovle