Search code examples
javamysqlbooleanresultset

ResultSet in Java


I need help creating a boolean check for a method I made. I basically want it to return true if they have the specified EnumRank, but it's not working. Any suggestions?

EDIT: Both values are stored in VARCHARS

Code:

    public boolean hasRank(Player player, EnumRanks rank){
    if (!MySql.checkConnection()){
        return false;
    }
    try{
        String query = "SELECT RANK FROM `user_ranks` WHERE UUID= '" + player.getUniqueId() + "';";
        PreparedStatement statement = MySql.getConnection().prepareStatement(query);
        ResultSet result = statement.executeQuery();
        result.next();
        return result.getBoolean(rank.getSQLName());
        //return true - So I can use this method
    }
    catch (SQLException e){
        //Nothing
    }
    return false;
}

Solution

  • Add the rank to the query, and you're using PreparedStatement so use bind parameters. You can use result.next() to check if the query returns a result and you should use the finally block to close your Statement and ResultSet (and Connection). And don't silently swallow Exception(s). Something like

    public boolean hasRank(Player player, EnumRanks rank) {
        if (!MySql.checkConnection()) {
            return false;
        }
        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet result = null;
        String query = "SELECT RANK FROM `user_ranks` WHERE UUID=? AND RANK=?";
        try {
            conn = MySql.getConnection();
            statement = conn.prepareStatement(query);
            statement.setString(1, player.getUniqueId());
            statement.setString(2, rank.getSQLName());
            result = statement.executeQuery();
            return result.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }