File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC 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
Bookmark "getting ID after Insert." Watch "getting ID after Insert." New topic
Author

getting ID after Insert.

dar
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.
stmt.executeUpdate();
...
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:
Texts{
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
Dan
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">http://java.sun.com/j2se/1.4/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String,%20int)
followed by
http://java.sun.com/j2se/1.4/docs/api/java/sql/Statement.html#getGeneratedKeys()
Otherwise your stuck with the above posts.
Jamie
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: getting ID after Insert.
 
Similar Threads
Before insert Trigger
altering a GUI object without triggering the listener
Having trouble using Dates in SQL
Question on insert records into table using java
getting Primary key when inserting