Is there a cross database platform way to get the primary key of the record you have just inserted?
I noted that this answer says that you can get it by Calling
extraneon's answer, although correct, doesn't work for Oracle.
The way you do this for Oracle is:
String key[] = {"ID"}; //put the name of the primary key column
ps = con.prepareStatement(insertQuery, key);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
generatedKey = rs.getLong(1);
}
for oracle, Hibernate uses NEXT_VALUE from a sequence if you have mapped a sequence for PKEY value generation.
Not sure what it does for MySQL or MS SQL server
For databases that conform to SQL-99, you can use identity columns: CREATE TABLE sometable (id INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 101) PRIMARY KEY, ...
Use getGeneratedKeys() to retrieve the key that was just inserted with executeUpdate(String sql, int autoGeneratedKeys). Use Statement.RETURN_GENERATED_KEYS for 2nd parameter to executeUpdate()
Spring provides some useful support for this operation and the reference guide seems to answer your question:
There is not a standard single way to create an appropriate PreparedStatement (which explains why the method signature is the way it is). An example that works on Oracle and may not work on other platforms is...
I've tested this example on MySQL and it works there too, but I can't speak for other platforms.
Have you tried the Statement.executeUpdate() and Statement.getGeneratedKeys() methods? There is a developerWorks article that mentions the approach.
Also, in JDBC 4.0 Sun added the row_id feature that allows you to get a unique handle on a row. The feature is supported by Oracle and DB2. For sql server you will probably need a third party driver such as this one.
Good luck!
Just declare id column as id integer not NULL primary key auto_increment
after this execute this code
ResultSet ds=st.executeQuery("select * from user");
while(ds.next())
{
ds.last();
System.out.println("please note down your registration id which is "+ds.getInt("id"));
}
ds.close();
the above code will show you the current row's id
if you remove ds.last()
than it will show all values of id column