javamysqlminecraftbungeecord

check row if not exist mysql and got output to boolean bukkit


I have tried this so many times but I never did it, this is my code

public static Boolean checkhaveguild(String name) {
    try {
        Statement statement = connection.createStatement();
        PreparedStatement ps = connection.prepareStatement("SELECT * FROM guild");
        System.out.println(statement.execute("SELECT * FROM guild WHERE name = "+name+""));
        System.out.println("----------");
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return false;
}

I am doing a guild plugin on BungeeCord and getting data from MySQL The code is about checking if the row does not exist and output to boolean


Solution

  • I'd suggest you to learn more about the basics of programming in Java! Minecraft is a great way to start into programming, but you should be interested in doing things properly.

    public static boolean hasGuild(String name) {
            PreparedStatement statement = null;
            ResultSet resultSet = null;
            try {
                statement = connection.prepareStatement("SELECT COUNT(name) FROM guild WHERE name = ?");
                statement.setString(1, name);
    
                resultSet = statement.executeQuery();
                if (resultSet.next()) return resultSet.getInt(1) > 0;
            } catch (SQLException e) {
                // TODO properly handle exception
            } finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        // TODO properly handle exception
                    }
                }
    
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        // TODO properly handle exception
                    }
                }
            }
            return false;
        }
    

    Some thoughts on what this code is doing:

    Some thoughts you should make yourself: