Retreivethe primary key the I just stored

If I just stored a new record in an auto-increment field, and I want to store the same field in another table (as a foreign key) how do I do that? It sounds like something stupid, yet the solution seems complex
[232 byte] By [Octaviana] at [2007-10-3 4:18:21]
# 1
does not the create method you are using return the object it has just created
r035198xa at 2007-7-14 22:20:01 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

String insertStatement = "INSERT INTO thread (thread_id, subject, started_by) VALUES ( ' ' ,' "+subject+" ' ,111 )";

stmt.executeUpdate(insertStatement, stmt.RETURN_GENERATED_KEYS);

ResultSet key = stmt.getGeneratedKeys();

key.next();

topic_id = key.getLong(1);

This did it....I just need to check out how portable JDBC really is

Octaviana at 2007-7-14 22:20:01 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3

> String insertStatement = "INSERT INTO thread

> (thread_id, subject, started_by) VALUES ( ' ' ,'

> "+subject+" ' ,111 )";

>

> stmt.executeUpdate(insertStatement,

> ent, stmt.RETURN_GENERATED_KEYS);

>

> ResultSet key = stmt.getGeneratedKeys();

> key.next();

> topic_id = key.getLong(1);

>

>

>

> This did it....I just need to check out how portable

> JDBC really is

I recommend using PreparedStatement to handle your insert statement.

And Yes. We do not recommend using auto-number field.

:D

TikkyChaia at 2007-7-14 22:20:01 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4

> And Yes. We do not recommend using auto-number

> field.

>

Wait-aminute here...

No. We do recommend using autonumber fields (surrogate keys). When used appropriately.

I recommend the following thread which has a detailed discussion about this very point http://forum.java.sun.com/thread.jspa?threadID=763655

cotton.ma at 2007-7-14 22:20:01 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5

Your solution is fine for JDBC 3.0, but the getGeneratedKeys() was not available prior to this.

The alternative is to obtain the key first using database specific SQL (e.g. select from dual in oracle), then use the key in your insert statement.

Use of prepated statements is definitely good. Not sure why TikkiChai is against using auto number fields (other than it can cause a few problems if you reset your sequence).

You may want to check out dbunit for unit testing JDBC code. http://dbunit.sourceforge.net/

SteveNaivea at 2007-7-14 22:20:01 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...