sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo detectar ResultSet vacío de MySQL?

Simplemente verifique si ResultSet#next() devuelve verdadero. Por ejemplo

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;
}

que puedes usar de la siguiente manera

if (userDAO.exist(username, password)) {
    // Proceed with login?
} else {
    // Show error?
}

Alternativamente, también podría dejar que devuelva un User completo. o null si no hay ninguno Por ejemplo

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, dateOfBirth 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.getDate("dateOfBirth"));
        }
    } finally {
        close(resultSet, statement, connection);
    }

    return user;
}

con

User user = userDAO.find(username, password);

if (user != null) {
    // Proceed with login?
} else {
    // Show error?
}