views:

325

answers:

3

Hi all.

Have a linking (or ref) table which has a dual primary key. Need to return the last primary key which was auto generated from the current connection in a selected table. This is in java. The database is in MS Access if that makes a difference. Sorry for the rushed description, but our team is working to a tight schedule.

Any links or suggestions would be gladly appreciated.

EDIT:

The database is populated using SQL. We enter the data for one form, but we do not know the auto generated number. Need to find out what this was so it can be entered into the ref table. We only know half the composite key, which is why we need the second one.

Edit:

Re the best answer so far (cant seem to comment). I get the following error... "Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException"

Any Advice?

A: 

Put both values for the composite key into an array of Object with two elements and return that.

Alternatively, put the new composite key in the instance you just saved and return that.

Aaron Digulla
+2  A: 

Statement.getGeneratedKeys() should do the trick...

ammoQ
+2  A: 

You need to do two things. First, you'll have to pass in an extra parameter when preparing your statement or executing your statement. If you're using prepared statements, do the following:

stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

If you're not using prepared statements, do the following when you call executeUpdate():

stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

After you execute your statement, you can call

ResultSet rs = stmt.getGeneratedKeys()

This will give you a result set that contains any of the keys that were generated.

I haven't tried this approach with Access, but it works fine with SQL Server identity columns.

Clint Miller