I am trying to do a SELECT using PreparedStatement, but not getting any results back, despite the data being present. If I use Statement instead, I get the desired results, so not sure why I don’t get anything with the PreparedStatement.
Any ideas?
Here is my code:
String species = "Snail";
PreparedStatement preparedStatement = con.prepareStatement("Select * from lifeforms where species=?",PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, species);
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
Also – I have tried just
resultSet = preparedStatement.execute();
But this won’t compile, saying I must change resultSet to expect a boolean value.
Any insights into this would be greatly appreciated.
Sorry if this is something obvious, but I have read the docs until I am almost unconscious, and I’m only just learning java.
Ah so I have finally found the answer to this question – in case anyone else is stuck on the same thing..
The
execute()method has no return value, although the compiler was suggesting it expected a boolean return value. Maybe it just returns true or false for successful or not?The
executeUpdate()method returns an int value of the number of records updated/inserted or deleted.To get the result set of a query statement (e.g. Select * from someTable), use the
ResultSet rs = preparedStatement.executeQuery()method.This will return the actual query results into a ResultSet variable.