[MySQL] See if player is in a table

Discussion in 'Plugin Development' started by macproman();, Dec 14, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    macproman();

    Hai everyone!

    So after a while, I have finally figured out the "basics" or connecting to a MySQL database and adding player names, etc.

    So. I would like to learn how I can see if a table contains a player name. For example, if the player types /potato it would get the table "test" and see if the senders name is in there. If it is, it would them send the sender a message saying "You're in the table!"

    Thanks in advance,

    - Myles
     
  2. Offline

    ItsMattHogan

    I pulled this from my Bukkit Plugin util API;

    Code:
    /**
    * This method is used to check if a player
    * is in a table.
    *
    * @param player   the player to look up
    * @param table    the table
    * @return if the player is in the table
    */
    public static boolean tableContainsPlayer(Player player,  String table) {
        SQLManager.openConnection();
    
        try {
            Statement statement = SQLManager.getConnection().createStatement();
            ResultSet result = statement.executeQuery("SELECT * FROM `" + table + "` WHERE `uuid` = '"
                    + player.getUniqueId().toString() + "';");
    
            return result.next();
        } catch (SQLException exception) {
            exception.printStackTrace();
        } finally {
            SQLManager.closeConnection();
        }
    
        return false;
    }
    
    You'll have to change it up a bit as you don't have my SQLManager class.
     
  3. Offline

    joeygallegos

    @ItsMattHogan just stating that you should really be using prepared statements for that method.
     
  4. Offline

    mythbusterma

    @macproman();

    First of all, don't listen to @ItsMattHogan, that's not a very good idea.

    Second, use something along the lines of "SELECT * FROM <table> WHERE <username> = <value>" , then seeing if the result set is empty.

    Of course, use prepared statements and execute this query on another thread, unless you love server lag.
     
  5. Offline

    ItsMattHogan

    I'll starting using prepared statements, I only started to play with SQL a couple weeks ago. I usually use no-SQL databases such as MongoDB and Aerospike.

    Thanks.
     
    mythbusterma likes this.
Thread Status:
Not open for further replies.

Share This Page