Mysql
 sql >> Base de données >  >> RDS >> Mysql

Comment détecter un ResultSet vide depuis MySQL ?

Vérifiez simplement si ResultSet#next() renvoie vrai. Par exemple

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 vous pouvez utiliser comme suit

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

Alternativement, vous pouvez également le laisser renvoyer un User complet ou null s'il n'y en a pas. Par exemple

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

avec

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

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