Solved

JDBC Return Value

Posted on 2004-08-24
28
355 Views
Last Modified: 2008-01-16
Let's say I'm executing an INSERT statement on a table as such:

int successful = stmt.executeUpdate(sqlStmt);

In this statment, I'm creating a record which has field which increments.  How can I return this value to the application so that I can process adding sub-records which are tied to this id?

Thanks,
David
0
Comment
Question by:lomidien
  • 9
  • 8
  • 7
  • +1
28 Comments
 
LVL 12

Expert Comment

by:Giant2
ID: 11889521
After the insert.
Make a SELECT statement taking this incremented field.

Giant.
0
 
LVL 92

Expert Comment

by:objects
ID: 11889533
try:

ResultSet rs = stmt.getGeneratedKeys();
0
 
LVL 92

Expert Comment

by:objects
ID: 11889534
what database?
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889535
maybe:
public int executeUpdate(String sql, int autoGeneratedKeys)

and then:
public ResultSet getGeneratedKeys()
0
 

Author Comment

by:lomidien
ID: 11889545
SQL Server 2000 (stupid omission from me)

I tried getGeneratedKeys() and got the following:

java.lang.AbstractMethodError: com.microsoft.jdbc.base.BaseStatement.getGeneratedKeys()Ljava/sql/ResultSet;
        at PreProduction.FMS.Panels.PartsMgmt.CreatePIF.SubmitPIFClicked(CreatePIF.java:422)
        at PreProduction.FMS.Panels.PartsMgmt.CreatePIF$2.mouseClicked(CreatePIF.java:201)
        at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:212)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889560
Do you have changed your executeUpdate into the following?
executeUpdate(String sql, int autoGeneratedKeys)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889561
In your case:

int successful = stmt.executeUpdate(sqlStmt,Statement.RETURN_GENERATED_KEYS);
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11889572
stmt.executeUpdate(sqlStmt);
I think we can not get the new key it inserts directly.

You can do it by

1.nextId = getNextID() by select max(id)+1 from table
2.use nextId insert to table1.
3.use nextId insert to table2.

Although it is easy to implement but this solution has drawback. it's possible that two client can get the same id and the second insert statement may throw SQLException: Key violation.

If your application is not serious and not much transaction at a time, you can do that. But If you need a perfect solution, you need to lock table by using Isolation Level and Transaction.

0
 
LVL 92

Expert Comment

by:objects
ID: 11889575
another option would be to use an sp that does the insert and returns the id to you.
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11889580
Oh! ignore my comment. follow objects,Giants
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889583
But my first solution?
>After the insert.
>Make a SELECT statement taking this incremented field.
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11889590
Keep my solution as the last way for you.

The getGeneratedKeys would be better solution.
0
 

Author Comment

by:lomidien
ID: 11889598
Ok, tried the following:

                int successful = stmt.executeUpdate(sqlStmt,Statement.RETURN_GENERATED_KEYS);
                ResultSet testSet = stmt.getGeneratedKeys();

And got the error above.  Actually, the statement will not execute with the 2nd argument inserted for some reason....same message each time.  The ID in the database table is marked as a primary key and is auto-incrementing, but it still yields an empty resultset.  

Thanks
David

0
 

Author Comment

by:lomidien
ID: 11889605
Sompol,

Yeah, thanks for your help.  I'm hoping not to go to that extent. :)  There would be a problem with concurrent users getting the same key because there is just enough transactions taking place that this would be somewhat likely.  :(

Thanks,
David
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 11889607
you could also try:

select @@identity

0
 

Author Comment

by:lomidien
ID: 11889618
What is "select @@identity"?
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889619
Is the driver you use to connect to your DB a type-3 ?
(I read that only this implements the fieature)
Try to use a type-3 JDBC Driver.
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11889620
I think stmt.getGeneratedKeys should be work. You may have to check whether jdbc driver support it or not.
and I think there should be jdbc that support because in EJB I can do that.
0
 
LVL 92

Expert Comment

by:objects
ID: 11889631
> What is "select @@identity"?

A query to return the last generated auto id

>  You may have to check whether jdbc driver support it or not.

appears that it doesn't.
prehaps also check you are running the latest version.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889637
>check whether jdbc driver support it or not
As I told before:
Is the driver you use to connect to your DB a type-3 ?
(I read that only this implements the feature)
Try to use a type-3 JDBC Driver.
0
 

Author Comment

by:lomidien
ID: 11889657
jdbc:microsoft:sqlserver

The latest JDBC driver from Microsoft I believe.  I can execute the query no problem, but when I try .returnGeneratedKeys() to a resultset, that's when I'm getting the errors.

:(
0
 

Author Comment

by:lomidien
ID: 11889660
I just read on http://forum.java.sun.com/thread.jsp?forum=48&thread=87438&start=15&range=15&hilite=false&q= that the Microsoft supplied JDBC driver does not support retrieval of autoGeneratedKeys.  How's that for convenience.  :(
0
 

Author Comment

by:lomidien
ID: 11889672
What about after the update quickly grabbing a "top value" for the field.  I understand that potentially this could be problematic, but the transactions are not so heavy that the time period spent seding in 4 columns and quickly running the query will make a difference.

Off the top of their head, does anyone know the syntax for a "top value" SQL Query?


David
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889675
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11889691
>after the update quickly grabbing a "top value" for the field
Mmmmhm.
In this manner you are not really secure to take the correct value.
Like I told in my first post:
>After the insert.
>Make a SELECT statement taking this incremented field.
the select must be secure (you can try to select using all the other field you use in the insert. (It's only an idea).
0
 
LVL 92

Expert Comment

by:objects
ID: 11889693
Did you try the query I posted above?
0
 

Author Comment

by:lomidien
ID: 11889722
SELECT @@identity works.

Objects, I'll have to admit, I thought it couldn't possibly work....just didn't seem like a valid query to me (in my mind).  Thanks a ton and thanks to every single person helping me with this problem at 2:00 AM.  I have a presentation in about 4 hours and was getting a little worried about this last hurdle.

Thanks again everyone!!!
David
0
 
LVL 92

Expert Comment

by:objects
ID: 11889740
Glad we could all help, good luck with your presentation :)
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now