Solved MySQL in my plugin is not working

Discussion in 'Spigot Plugin Development' started by Maxiceks, Sep 14, 2019.

  1. Hello, I just want to ask you how to make a MySQL in a plugin

    My code is not working...
    Sending it here

    Code (Java):
    Main.java

    package me.mejx;

    import java.util.ArrayList;
    import java.util.UUID;

    import org.bukkit.Bukkit;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.scoreboard.DisplaySlot;
    import org.bukkit.scoreboard.Scoreboard;

    import me.mejx.board.BoardPrepare;
    import me.mejx.build.BuildCommand;
    import me.mejx.build.BuildEvents;
    import me.mejx.christmas.VanoceCommand;
    import me.mejx.christmas.VanoceListener;
    import me.mejx.coins.CoinsCommand;
    import me.mejx.damage.DamageEvent;
    import me.mejx.join.JoinCommand;
    import me.mejx.join.JoinTeleporter;

    public class Main extends JavaPlugin {

        Main pl = this;

     
        public void onEnable() {
            MySQL.connect();
            MySQL.createTableCoins();
            MySQL.createTableKredit();      
         
         
            BuildCommand.list = new ArrayList<UUID>();

            this.saveDefaultConfig();
            this.saveConfig();
         
            this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
            this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new Receiver(this));

            this.getCommand("build").setExecutor(new BuildCommand(this));
            this.getCommand("oreo").setExecutor(new OreoCraft(this));
            this.getCommand("setjoin").setExecutor(new JoinCommand(this));
            this.getCommand("vanoce").setExecutor(new VanoceCommand(this));
            this.getCommand("lyze").setExecutor(new VanoceCommand(this));
            this.getCommand("coins").setExecutor(new CoinsCommand(this));
            this.getServer().getPluginManager().registerEvents(new BuildEvents(this), this);
            this.getServer().getPluginManager().registerEvents(new DamageEvent(this), this);
            this.getServer().getPluginManager().registerEvents(new JoinTeleporter(this), this);
            this.getServer().getPluginManager().registerEvents(new VanoceListener(this), this);
         

         
         
            Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
                public void run() {
                    for (Player players : Bukkit.getServer().getOnlinePlayers()) {
                        Scoreboard board = players.getScoreboard();
                        board.clearSlot(DisplaySlot.SIDEBAR);
                        players.setScoreboard(board);
                        BoardPrepare.giveBoard(players, pl);
                    }
                }
            }, 0L, 10L);
        }
     
        public void onDisable() {
            MySQL.disconnect();
        }
    }
     




    Code (Java):
    MySQL.java


    package me.mejx;

    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.sql.Connection;

    public class MySQL {

       public static Connection con;
       
       
       public static void connect() {
           if (isConnected()) {
               try {
                   con = DriverManager.getConnection("jdbc:mysql://secretip:3306/minecraft", "root", "password");
                   System.out.print("Mysql pripojena");
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
       }
       
       public static void disconnect() {
           if (isConnected()) {
               try {
                   con.close();
                   System.out.print("Mysql odpojena");
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
       }
       
       public static boolean isConnected() {
           return (con != null);
       }
       
       
       public static void createTableCoins() {
           try {
               PreparedStatement st = con.prepareStatement("CREATE TABLE IF NOT EXISTS oreocraft-coins (UUID VARCHAR(100), coins INT (16));");
               st.executeUpdate();
               st.executeQuery();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       
       public static void createTableKredit() {
           try {
               PreparedStatement st = con.prepareStatement("CREATE TABLE IF NOT EXISTS oreocraft-kredit (UUID VARCHAR(100), coins INT(16))");
               st.executeUpdate();
               st.executeQuery();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }

    }

     








    Code (Java):
    CoinsAPI.java


    package me.mejx.coins;

    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    import me.mejx.MySQL;

    public class CoinsAPI {

        public static int getCoins(String uuid) {
            try {
                PreparedStatement st = MySQL.con.prepareStatement("SELECT * FROM oreocraft-coins WHERE UUID = ?");
             
                st.setString(1, uuid);
                ResultSet rs = st.executeQuery();
                while (rs.next()) {
                    return rs.getInt("coins");
                }
             
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return -1;
        }
     
        public static void setCoins(String uuid, int coins) {
            if (getCoins(uuid) == -1) {
                try {
                    PreparedStatement st = MySQL.con.prepareStatement("INSERT INTO coins (UUID,coins) VALUES (?,?)");
                    st.setString(1, uuid);
                    st.setInt(2, coins);
                    st.executeUpdate();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } else {
                PreparedStatement st;
                try {
                    st = MySQL.con.prepareStatement("UPDATE coins SET coins = ? WHERE UUID = ?");
                    st.setString(2, uuid);
                    st.setInt(1, coins);
                    st.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
     
        public static void addCoins(String uuid, int coins) {
            setCoins(uuid, coins + getCoins(uuid));
         
        }

        public static void removeCoins(String uuid, int coins) {
            setCoins(uuid, getCoins(uuid) - coins);
        }
    }
     















    Code (Java):
    CoinsCommand.java




    package me.mejx.coins;

    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    import me.mejx.Main;

    public class CoinsCommand implements CommandExecutor {
        private final Main pl;    public CoinsCommand(Main pl) {this.pl = pl;}

        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            Player p = (Player) sender;
         
            if (cmd.getName().equalsIgnoreCase("coins")) {
                int coins = CoinsAPI.getCoins(p.getUniqueId().toString());
             
                p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&3Coins&f] &3Coins: &f" + coins));
            }
         
            return false;
        }

    }
     
     
    #1 Maxiceks, Sep 14, 2019
    Last edited: Sep 14, 2019
  2. You forgot a "!" at your connect method.
    Use this:
    Code (Text):
    public static void connect() {
           if (!isConnected()) {
               try {
                   con = DriverManager.getConnection("jdbc:mysql://secretip:3306/minecraft", "root", "password");
                   System.out.print("Mysql pripojena");
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
       }
    instead of this:
    Code (Text):
    public static void connect() {
           if (isConnected()) {
               try {
                   con = DriverManager.getConnection("jdbc:mysql://secretip:3306/minecraft", "root", "password");
                   System.out.print("Mysql pripojena");
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
       }
     
  3. Still nothing its saying me

    Code (Text):
    [11:41:42 WARN]: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    [11:41:42 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    [11:41:42 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    [11:41:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    [11:41:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    [11:41:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    [11:41:42 WARN]:        at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    [11:41:42 WARN]:        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:343)
    [11:41:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2334)
    [11:41:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2371)
    [11:41:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2163)
    [11:41:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
    [11:41:42 WARN]:        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    [11:41:42 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    [11:41:42 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    [11:41:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    [11:41:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    [11:41:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    [11:41:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:378)
    [11:41:42 WARN]:        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    [11:41:42 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:664)
    [11:41:42 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:247)
    [11:41:42 WARN]:        at me.mejx.MySQL.connect(MySQL.java:16)
    [11:41:42 WARN]:        at me.mejx.Main.onEnable(Main.java:28)
    [11:41:42 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321)
    [11:41:42 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340)
    [11:41:42 WARN]:        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405)
    [11:41:42 WARN]:        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357)
    [11:41:42 WARN]:        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317)
    [11:41:42 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414)
    [11:41:42 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378)
    [11:41:42 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333)
    [11:41:42 WARN]:        at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263)
    [11:41:42 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525)
    [11:41:42 WARN]:        at java.lang.Thread.run(Thread.java:748)
    [11:41:42 WARN]: Caused by: java.net.ConnectException: Connection refused (Connection refused)
    [11:41:42 WARN]:        at java.net.PlainSocketImpl.socketConnect(Native Method)
    [11:41:42 WARN]:        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    [11:41:42 WARN]:        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    [11:41:42 WARN]:        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    [11:41:42 WARN]:        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    [11:41:42 WARN]:        at java.net.Socket.connect(Socket.java:589)
    [11:41:42 WARN]:        at java.net.Socket.connect(Socket.java:538)
    [11:41:42 WARN]:        at java.net.Socket.<init>(Socket.java:434)
    [11:41:42 WARN]:        at java.net.Socket.<init>(Socket.java:244)
    [11:41:42 WARN]:        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:254)
    [11:41:42 WARN]:        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:292)
    [11:41:42 WARN]:        ... 27 more
    [11:41:42 ERROR]: Error occurred while enabling OreoCraft v5.62 (Is it up to date?)
    java.lang.NullPointerException
            at me.mejx.MySQL.createTableCoins(MySQL.java:42) ~[?:?]
            at me.mejx.Main.onEnable(Main.java:29) ~[?:?]
            at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357) [server.jar:git-Spigot-db6de12-18fbb24]
            at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263) [server.jar:git-Spigot-db6de12-18fbb24]
            at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525) [server.jar:git-Spigot-db6de12-18fbb24]
     
  4. Did you realy checked the Login Data for your database?
    Also put a check for your connection, before executing the statement.
     
  5. Ok my mistake i wrote wrong IP
    Thank you very much
     
  6. Sorry, one thing else
    How i check if player is in MySQL Database if he join?
     
  7. You can check existing players like that:
    Code (Text):
    PreparedStatement st = MySQL.con.prepareStatement("SELECT * FROM oreocraft-coins WHERE UUID = ?");
                st.setString(1, uuid);
                ResultSet rs = st.executeQuery();
                if(!rs.next()) {
                    //He is not existing, so insert
                } else {
                    //He is existing
                }
             
     
  8. Do not forget to execute the queries asynchronously.
     
  9. He event cant code object oriented, so thats not pretty helpful.
     
  10. I do not get what you mean and how object orientated programming is related to running code asynchronously.
     
  11. To handle with asynchronously code is pretty hard. So why should he do that? He is actually learning mysql.
     
  12. Because otherwise he is going to freeze the whole server while he does the query? And setting up a BukkitRunnable/BukkitScheduler is not hard.
     
  13. Dear Patrick,

    are you querying the datas of the player every nanosecond?
    You just need to query the datas of a player at the begin, you gonna handle with that and if the player left the server/game you can upload his datas to the database.
    Of course there are some exceptions, where you should use query while being online. But for things like that its not important.
     
  14. Yes, and when the player quits, you are going to need to connect to the MySQL server (since you should always close the connection when you do not need it anymore), which takes time and freezes the server. Then you need to do the query (which also takes some time and freezes the server again). In total this will make other players experience lag spikes. If the MySQL server is far away from the Minecraft server, the lag spike will be even longer and if the server is huge and there are much players, there will be even more lag spikes. It is like doing Thread#sleep(long) on the main thread every few minutes.

    To avoid these lag spikes, you can setup a BukkitScheduler/BukkitRunnable which is super easy. Java 8 also have CompletableFuture which makes these things easier.
    One more thing: Why do huge plugins like LuckPerms also do their queries asynchronously when it is not necessary?
     
    #15 patri9ck, Sep 14, 2019
    Last edited: Sep 14, 2019