my dog learned polymorphism*
The moose likes JDBC 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
Bookmark "getGeneratedKeys() causing exception" Watch "getGeneratedKeys() causing exception" New topic
Author

getGeneratedKeys() causing exception

Siby George
Greenhorn

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 && resultSet.next()) {
logId = resultSet.getLong(1);
}


Line: getGeneratedKeys() is causing exception:

com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getGeneratedKeys(SQLServerStatement.java:2002)

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

Thanks
Siby
Karthik Shiraly
Ranch Hand

Joined: Apr 04, 2009
Posts: 529
    
    6
Should be
Siby George
Greenhorn

Joined: Mar 22, 2011
Posts: 14
Thanks, that was the solution
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: getGeneratedKeys() causing exception