Brian Sweeney
Brian Sweeney

Reputation: 6793

Strange Exception on getGeneratedKeys() with JDBC for MySQL 5.1

I'm using JDBC to insert a row into a MYSQL database. I build a parameterized command, execute it and attempt to retrieve the auto generated keys as follows:

String sql = "INSERT IGNORE INTO `users` (`email`, `pass-hash`) VALUES (?, ?)";
Connection conn = SQLAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, login);
ps.setString(2, passHash);

int count = ps.executeUpdate();

if (count == 1) {
    ResultSet rs = ps.getGeneratedKeys();
    rs.next();
         //some more stuff...
}

For some reason, I get the following SQLException on the line containing ResultSet rs = ps.getGeneratedKeys();:

!Statement.Generated Keys Not Requested!

Any thoughts? When I run the same query, as generated by running the app through the debugger, in a MySQL browser it executes without incident.

Thanks, brian

Upvotes: 2

Views: 2338

Answers (2)

Trey
Trey

Reputation: 11158

I think you want to call prepareStatement(sql, RETURN_GENERATED_KEYS)

Upvotes: 5

Gentle Y
Gentle Y

Reputation: 331

The method getGeneratedKeys() is in JDBC 3.0 API and this is not useable on all platform.

And PreparedStatement does not have getGenerateKeys() 's implement and it is only in Statement and is a abstract method.

Here is a topic about this method's issue : http://forums.sun.com/thread.jspa?threadID=260818

Upvotes: 0

Related Questions