简体   繁体   中英

How to check whether or not a mysql entry exists

i tried to check whether or not a Player is in a MySQL database.

My code for that was this:

    public boolean existUUID() {
        List<String> list = new ArrayList<>();

        try {
            PreparedStatement state = MySQL.c.prepareStatement("SELECT * FROM players");
            state.setString(1, this.uuid.toString());

            ResultSet result = state.executeQuery();

            while (result.next()) {
                list.add(result.getString("uuid"));
            }
            result.close();
            state.close();


        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list.contains(this.uuid);
    }

uuid is setted in the Class and a player with the uuid does exist in the database

Creating a list every time you call the method (a singleton ArrayList) is a waste of memory, even if you don't notice it much. You also don't need to pass an index or value in your statement if there are no values to insert in your query. If you try to check only one uuid you don't have to use a while-loop. You can also use a try-with-resource to close your statements when they are no longer needed. If you want to read values from a SQL database, I would always recommend using a consumer. I have attached an example:

public void registeredUniqueId(UUID uniqueId, Consumer<Boolean> registered) {
    try (PreparedStatement statement =  connection.prepareStatement(String.format("SELECT * FROM players WHERE UUID='%s'", uniqueId.toString())); ResultSet resultSet = statement.executeQuery()) {

    if (resultSet.next() && resultSet.getString("UUID") != null) {
      registered.accept(true);
    }
  } catch (SQLException ex) {
    ex.printStackTrace();
    registered.accept(false);
  }
}

I recommend to always run MySQL queries asynchronously. In my example everything is executed synchronously.

I would suggest the following code & query

 public boolean existUUID() {
        List<String> list = new ArrayList<>();

        try {
            PreparedStatement state = MySQL.c.prepareStatement("SELECT * FROM players where uuid=?");
            state.setString(1, this.uuid.toString());

            ResultSet result = state.executeQuery();

            while (result.next()) {
                return true
            }
            return false


        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally
        {
            result.close();
            state.close();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM