sql >> Database teknologi >  >> RDS >> Mysql

Hvordan opdager man tomt ResultSet fra MySQL?

Bare tjek om ResultSet#next() returnerer sandt. F.eks.

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

som du kan bruge som følger

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

Alternativt kan du også lade den returnere en fuldgyldig User eller null hvis der ikke er nogen. F.eks.

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

med

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

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



  1. Tilslutning til MySQL-database ved hjælp af PHP fra en Android-enhed

  2. Sender FieldName som parameter i MySQL Stored Procedure

  3. Find lignende billeder i (ren) PHP / MySQL

  4. Postgres generere_serie