【问题标题】:How to check whether or not a mysql entry exists如何检查mysql条目是否存在
【发布时间】:2020-03-01 11:26:59
【问题描述】:

我尝试检查播放器是否在 MySQL 数据库中。

我的代码是这样的:

    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,并且数据库中确实存在具有uuid的玩家

【问题讨论】:

  • 你为什么要这样做?

标签: mysql sql minecraft


【解决方案1】:

每次调用方法时创建一个列表(单例 ArrayList)是一种内存浪费,即使您没有注意到太多。如果您的查询中没有要插入的值,您也不需要在语句中传递索引或值。如果您尝试只检查一个 uuid,则不必使用 while 循环。您还可以使用 try-with-resource 在不再需要时关闭语句。如果你想从 SQL 数据库中读取值,我总是建议使用消费者。我附上了一个例子:

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

我建议始终异步运行 MySQL 查询。在我的示例中,所有内容都是同步执行的。

【讨论】:

    【解决方案2】:

    我会建议以下代码和查询

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

    【讨论】:

    • 所以你需要发布一些。更多的细节,因为这里有其他问题。
    • 添加一些关于表结构的更多细节,你得到的错误(如果你得到一个)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多