The moose likes JDBC and Relational Databases and the fly likes getGeneratedKeys() causing exception 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 "getGeneratedKeys() causing exception" Watch "getGeneratedKeys() causing exception" New topic

getGeneratedKeys() causing exception

Siby George

Joined: Mar 22, 2011
Posts: 14
Hi All,
I am in a very strange situation. I am using MSSQL as DB and when I try to retrieve inserted record's key using getGeneratedKeys() I get error. I searched for an answer but of no luck.

Code snippet:

pstmt = conn.prepareStatement(query);
int insertCount = pstmt.executeUpdate(); // execute insert statement
System.out.println("Insert Count:" + insertCount);
ResultSet resultSet = pstmt.getGeneratedKeys();
if (resultSet != null && {
logId = resultSet.getLong(1);

Line: getGeneratedKeys() is causing exception: The statement must be executed before any results can be obtained.

I dont see this as a jdbc driver issue as I am using latest driver: sqljdbc4.jar and have tried the same situation in hibernate and that works

Karthik Shiraly

Joined: Apr 04, 2009
Posts: 874

Should be
Siby George

Joined: Mar 22, 2011
Posts: 14
Thanks, that was the solution
I agree. Here's the link:
subject: getGeneratedKeys() causing exception
It's not a secret anymore!