File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes getting ID after Insert. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "getting ID after Insert." Watch "getting ID after Insert." New topic

getting ID after Insert.

Ranch Hand

Joined: Nov 08, 2001
Posts: 45
Hi all.
Does somebody know, how to solve this problem:
In my code I insert a new record into the table.
String sqlStmt = "INSERT INTO Texts (text) VALUES (?)";
PreparedStatement stmt = getConnection().prepareStatement(sqlStmt);
stmt.setString(1,newtext); //newtext is String.
And right after(immediatly) I need to get text_ID (that is given by DB Server) number
of this new created Text-record. I don't use 'SELECT text_ID from Where text = newtext',
because this value (the column 'text') maybe more than one.
They maybe works more users at the same time,
therefore I cann't use 'sort by text_ID' and get the last record.
Table looks like:
text_id // column is PrimKey and automatic from DB Server
text // 'normal' column. Some string value. Maybe duplicate.
Thanks for your idea, answer.
Daniel Dunleavy
Ranch Hand

Joined: Mar 13, 2001
Posts: 276
This has been answered a number of times.
Do a search on jdbc for identity (sql svr), sequence (oracle), etc
basically you can do the insert in a stored procedure and return the key
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

if it is possible for you to use the jdk1.4SE then you could consider this:
java.lang.String,%20int)" TARGET=_blank rel="nofollow">,%20int)
followed by
Otherwise your stuck with the above posts.
I agree. Here's the link:
subject: getting ID after Insert.
It's not a secret anymore!