Shifting the cursor forth and back to determine the amount of rows is not the normal JDBC practice. The normal JDBC practice is to map the ResultSet
to a List
of value objects each representing a table row entity and then just use the List
methods to determine if there are any rows.
For example:
List<User> users = userDAO.list();
if (users.isEmpty()) {
// It is empty!
if (users.size() == 1) {
// It has only one row!
} else {
// It has more than one row!
}
where the list()
method look like as follows:
public List<User> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong("id"));
user.setName(resultSet.getString("name"));
// ...
users.add(user);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return users;
}
Also see this answer for other JDBC examples.