Empty or not, but doing the following is always faulty:
resultSet = statement.executeQuery(sql);
string = resultSet.getString(1); // Epic fail. The cursor isn't set yet.
This is not a bug. This is documented behaviour. Every decent JDBC tutorial mentions it. You need to set the ResultSet's cursor using next()
before being able to access any data.
If you're actually interested whether the supposedly unique row exist or not, then just check the outcome of next()
. For example in a fictive UserDAO
class:
public boolean exist(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
close(resultSet, statement, connection);
}
return exist;
}
If you actually expect only zero or one row, then just do something like:
public User find(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, age FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User(
resultSet.getLong("id"),
resultSet.getString("username"),
resultSet.getString("email"),
resultSet.getInteger("age"));
}
} finally {
close(resultSet, statement, connection);
}
return user;
}
and then just handle it accordingly in the business/domain object, e.g.
User user = userDAO.find(username, password);
if (user != null) {
// Login?
} else {
// Show error?
}
If you actually expect only zero or many rows, then just do something like:
public List<User> list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, age FROM user");
resultSet = statement.executeQuery();
while (resultSet.next()) {
users.add(new User(
resultSet.getLong("id"),
resultSet.getString("username"),
resultSet.getString("email"),
resultSet.getInteger("age")));
}
} finally {
close(resultSet, statement, connection);
}
return users;
}
and then just handle it accordingly in the business/domain object, e.g.
List<User> users = userDAO.list();
if (!users.isEmpty()) {
int count = users.size();
} else {
// Help, no users?
}