Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve id of record just inserted into a Java DB (Derby) database

Tags:

sql

jdbc

javadb

I am connecting to a Java DB database with JDBC and want to retrieve the id (which is on auto increment) of the last record inserted.

I see this is a common question, but I see solutions using for example MS SQL Server, what is the equivalent for Java DB?

like image 288
Kryptic Avatar asked Feb 04 '11 05:02

Kryptic


People also ask

Where does Apache Derby store data?

A Derby database is stored in files that live in a directory of the same name as the database. Database directories typically live in system directories. Contains files that make up the database transaction log, used internally for data recovery (not the same thing as the error log).


3 Answers

No need to use a DBMS specific SQL for that.

That's what getGeneratedKeys() is for.

When preparing your statement you pass the name(s) of the auto-generated columns which you can then retrieve using getGeneratedKeys()

PreparedStatement pstmt = connection.prepareStatement(
     "insert into some_table (col1, col2, ..) values (....)", 
      new String[] { "ID_COLUMN"} ); 

pstmt.executeUpdate();

ResultSet rs = pstmt.getGeneratedKeys(); // will return the ID in ID_COLUMN

Note that column names are case sensitive in this case (in Derby and many other DBMS).
new String[] { "ID_COLUMN"} is something different than new String[] { "id_column"}


Alternatively you can also use:

connection.prepareStatement("INSERT ...", PreparedStatement.RETURN_GENERATED_KEYS);
like image 141
a_horse_with_no_name Avatar answered Oct 29 '22 08:10

a_horse_with_no_name


You may be able to get what you're looking for using the IDENTITY_VAL_LOCAL function. (Derby Reference)

This function is supposed to return "the most recently assigned value of an identity column for a connection, where the assignment occurred as a result of a single row INSERT statement using a VALUES clause."

It's worth noting that this function will return DECIMAL(31,0), regardless of the actual data type of the corresponding identity column.

Also, this only works for single row inserts that contain a VALUES clause.

like image 35
nybbler Avatar answered Oct 29 '22 07:10

nybbler


For those who have issues getting the generated autoincrement id like I used to for Java Derby, my answer can be of help.

stmt.executeUpdate("INSERT INTO xx(Name) VALUES ('Joe')", Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
  int autoKey = rs.getInt(1); //this is the auto-generated key for your use
} 

Answer copied from here

like image 1
leeCoder Avatar answered Oct 29 '22 09:10

leeCoder