Tutorial Using MySQL In your Plugins!

Discussion in 'Resources' started by -_Husky_-, Mar 1, 2013.

Thread Status:
Not open for further replies.
  1. Not at all. My query's only purpose is that of checking if the Location entry is the same as the location of the player. It's an if inside an event handler.
     
  2. Offline

    pie_flavor

    @dadus33 RingOfStorms is correct. You already know that the location is correct, because that is part of the query. If the result set is closed, then it is empty, so the location is not correct.
     
  3. I can see that, but how can I check if the location of the player is that found inside the database? I mean, without the exception.
     
  4. Offline

    pie_flavor

    @dadus33
    Code:
    ResultSet set = l.statement.executeQuery("SELECT Location FROM LaunchPlate WHERE Location = '"+ serializeLoc(loc.getBlock().getLocation())+"';");
    if (!set.next()) {
    //code here
     
  5. Offline

    RingOfStorms

    I still don't get your query. You are selecting the Location column where the Location column is equal to something you already know. Maybe you should just COUNT rather than select the same exact column that you already know.

    SELECT COUNT(*) FROM LaunchPlate WHERE Location = ....

    This way you just get the number matching, and are also not having the SQL server send a bunch of useless data.

    And another thing, your second line with the IF statement doesn't make a whole lot of sense.
    if(player.hasPermission(l.p)&& set.getString("Location").equals(serializeLoc(loc.getBlock().getLocation()))){

    You should probably check the permissions FIRST before you start using sql as you are just wasting bandwidth if you do absolutely nothing with the result due to no permission. And then the second part of your if statement will never be false because you've already had SQL return you a location that does equal the one you just asked for. What you wrote there was basically
    if(player has permission && true == true)

    So use count instead and format it more like

    Pseudo code:
    Code:
    if(player has permission) {
       Result ... "SELECT COUNT(*)..."
       if(result > 0) {
          /code
       }
    }
    
    @dadus33
    @pie_flavor
     
  6. Look, I'm not an SQL expert, actualy, I'm more of a begginer, so I don't kinda understand what you mean. I want to check if a player's location exists inside the database. As far as I know, the COUNT(*) function will return the number of entries in a table, and I really don't know how that would be useful to me. I don't want to get the location from the table, because, as you said, I already know it. However, I want to CHECK if it exists. But thank you for the idea of putting the permission thingy first.

    EDIT:
    Eh, I think I got it now. Using the COUNT function I can check wheter the location is present in the db or not. If it is, it will return 1, else, 0. Thank you so much!

    Hmm, guys, how can I get the value of a result set? I mean, I can't just do 'if (res>0)'. And getInt doesn't work...

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Dec 20, 2015
    RingOfStorms likes this.
  7. Offline

    pie_flavor

    @dadus33
    Code:
    if (result.next() && result.getInt("value") > 0) {
    A ResultSet has a pointer. The value you pass, in this case "value", is the column label; the pointer designates the row number. It starts before the first one. The boolean function next() moves it one farther, and returns false if it is now past the entire set.
     
  8. Offline

    RingOfStorms

    if (getResultSet().first() && getResultSet().getInt(1) > 0)
    Same as above but doesn't require you to know column 1's name which makes it a little easier to remember and use elsewhere
     
  9. Offline

    pie_flavor

    @RingOfStorms Except the correct column isn't necessarily the first one.
    However, he does know the name.
     
  10. Thanks guys, solved it. Just used res.getInt(1) and it worked.
     
  11. Offline

    pie_flavor

    @dadus33 I would also hope you are not doing IO on the database on the main thread, and instead use some sort of hashmap to store the data
     
  12. Offline

    flamboo

    Hey guys, Just started using this lib and it is great :) I am having a problem with my code. I followed A YouTube video but I am getting some errors. Bellow is my code and the errors. I hope you can help me.

    Code:
    package me.flamboo.WebbedMCAuth;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    import org.bukkit.ChatColor;
    import org.bukkit.Server;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.command.ConsoleCommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    import code.husky.mysql.MySQL;
    public class Main extends JavaPlugin implements Listener{
          
        public String sqhost = getConfig().getString("Database.Host");
        public String sqport = getConfig().getString("Database.port");
        public String sqdb = getConfig().getString("Database.Database");
        public String squser = getConfig().getString("Database.User");
        public String sqpass = getConfig().getString("Database.Password");
        public String sqtable = getConfig().getString("Database.Table");
           public MySQL db;
           public boolean logDB = true ;
              public void onEnable(){
                   Server server = getServer();
            ConsoleCommandSender console = server.getConsoleSender();
                   console.sendMessage(ChatColor.RED + getDescription().getName());
            console.sendMessage(ChatColor.RED + "Version " + getDescription().getVersion());
                 PluginManager pm = getServer().getPluginManager();
          pm.registerEvents(this, this);
               FileConfiguration config = getConfig();
               config.addDefault("Database.Host", "localhost");
          config.addDefault("Database.Port", 3306);
          config.addDefault("Database.Database", "test");
          config.addDefault("Database.User", "root");
          config.addDefault("Database.Password", "fliplip1");
          config.addDefault("Database.Table", "test");
          config.options().copyDefaults(true);
          saveConfig();
               try {
            this.setupDB();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            this.logDB = false;
            console.sendMessage("Error (1) :" + e);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            this.logDB = false;
            e.printStackTrace();
            console.sendMessage("Error (2) :" + e);
        }
              }
              public void onEnalbe(){
              }
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] arg)
          {
            Player player = (Player)sender;
            Server server = getServer();
            ConsoleCommandSender console = server.getConsoleSender();
            if (commandLabel.equalsIgnoreCase("auth")) {
                if (player.hasPermission("auth.can")) {
                    if(arg.length == 0){
                        player.sendMessage(ChatColor.GRAY + "You need to enter your site ID");
                    }
                    else if(arg.length == 1){
                        Player ap = player.getServer().getPlayer(arg[0]);
                        String pname = player.getDisplayName().toLowerCase();
                        try{
                        if(!this.db.checkConnection())
                            this.db.openConnection();
                        Statement statement = this.db.getConnection().createStatement();
                        statement.executeUpdate("UPDATE '"+sqtable+" SET 'Auth'='1' WHERE 'Site'="+ap+"';");
                        statement.executeUpdate("UPDATE '"+sqtable+" SET 'Name'='"+pname+"' WHERE 'Site'="+ap+"';");
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            this.logDB = false;
                            console.sendMessage("Error: (3) " + e);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            this.logDB = false;
                            e.printStackTrace();
                            console.sendMessage("Error: (4) " + e);
                        }
                    }
                }
                else
                {
                }
            }
            return true;
          }
            public void setupDB() throws SQLException, ClassNotFoundException{
            this.db = new MySQL(this, sqhost, sqport, sqdb, squser, sqpass);
            this.db.openConnection();
            Statement statement = this.db.getConnection().createStatement();
            statement.executeUpdate("CREATE TABLE IF NOT EXISTS '"+sqtable+"' ('Site' int,'name' varchar(32),'Auth' int)");
            statement.close();
        }
    }
    Code:
    [18:54:55 INFO]: [WebbedMC_Auth] Enabling WebbedMC_Auth v1.0
    [18:54:55 INFO]: WebbedMC_Auth
    [18:54:55 INFO]: Version 1.0
    [18:54:55 WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "null"'.
    [18:54:55 WARN]: at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    [18:54:55 WARN]: at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    [18:54:55 WARN]: at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    [18:54:55 WARN]: at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    [18:54:55 WARN]: at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    [18:54:55 WARN]: at com.mysql.jdbc.Util.getInstance(Util.java:382)
    [18:54:55 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
    [18:54:55 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    [18:54:55 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    [18:54:55 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    [18:54:55 WARN]: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:314)
    [18:54:55 WARN]: at java.sql.DriverManager.getConnection(DriverManager.java:571)
    [18:54:55 WARN]: at java.sql.DriverManager.getConnection(DriverManager.java:215)
    [18:54:55 WARN]: at code.husky.mysql.MySQL.openConnection(MySQL.java:58)
    [18:54:55 WARN]: at me.flamboo.WebbedMCAuth.Main.setupDB(Main.java:123)
    [18:54:55 WARN]: at me.flamboo.WebbedMCAuth.Main.onEnable(Main.java:60)
    [18:54:55 WARN]: at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321)
    [18:54:55 WARN]: at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340)
    [18:54:55 WARN]: at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405)
    [18:54:55 WARN]: at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:356)
    [18:54:55 WARN]: at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:316)
    [18:54:55 WARN]: at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:418)
    [18:54:55 WARN]: at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:382)
    [18:54:55 WARN]: at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:337)
    [18:54:55 WARN]: at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:256)
    [18:54:55 WARN]: at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:528)
    [18:54:55 WARN]: at java.lang.Thread.run(Thread.java:745)
    [18:54:55 WARN]: Caused by: java.lang.NumberFormatException: For input string: "null"
    [18:54:55 WARN]: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    [18:54:55 WARN]: at java.lang.Integer.parseInt(Integer.java:492)
    [18:54:55 WARN]: at java.lang.Integer.parseInt(Integer.java:527)
    [18:54:55 WARN]: at com.mysql.jdbc.NonRegisteringDriver.port(NonRegisteringDriver.java:831)
    [18:54:55 WARN]: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    [18:54:55 WARN]: ... 16 more
    
    the errors
     
  13. Offline

    Pocketkid2

    Code:
    MySQL MySQL = new MySQL(this, ip, port, name, user, pass);
            try {
                c = MySQL.openConnection();
            } catch (ClassNotFoundException e) {
                getLogger().severe("ClassNotFoundException");
            } catch (SQLException e) {
                getLogger().severe("SQLException");
            }
    When running this code the last log message is shown. I have checked so many times and I am using the same connection values loaded from a config as another mysql plugin that works fine on the same test server and test database.
     
  14. Offline

    FiberSprite

    Helloo There Bukkit Community, I was wondering how would i make it so it will add a player to the table on my mysql database but if the player is already on there do nothing?
     
    Last edited: Jul 24, 2015
  15. Offline

    Eos

    When the player first joins the server check if they exist in the table with SELECT * and if it they don't exist create a new table for them.
     
  16. Offline

    Konato_K

    @Eos Why would you select "*"?
     
  17. Offline

    WonderWaffleYT

    Are you still active on the forums? I need help
     
  18. Offline

    MCMatters

  19. Offline

    Konato_K

    @MCMatters Because it's slower, more overload to the database and unnecessary data sent?
     
  20. Offline

    shizleshizle

    Nice tutorial, worked. I only bumped into this small problem:


    Code:
     MySQL MySQL = new MySQL("host.name", "port", "database", "user", "pass");
        Connection c = null;
    
        @Override
        public void onEnable() {
            c = MySQL.openConnection();
    //Unhandled exception type ClassNotFoundException
    And btw, how do you close the connection? I assume it isnt as simple as c = MySQL.closeConnection(); (In onDisable())?
     
  21. Offline

    Zombie_Striker

    @shizleshizle
    If there is a "CNF" error, that means you imported the wrong thing. Can we see your imports?

    Also, to close a port I believe is "c.close()" or "c.closeConnection();".
     
  22. Offline

    DoggyCode™

    r
     
    Last edited: Dec 28, 2015
  23. Offline

    DoggyCode™

    I'm getting the "no database selected" error
    (
    Code:
    [21:35:59 WARN]: java.sql.SQLException: No database selected
    [21:35:59 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.j
    ava:1073)
    [21:35:59 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:
    3593)
    [21:35:59 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:
    3525)
    [21:35:59 WARN]:        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986)
    
    [21:35:59 WARN]:        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:21
    40)
    [21:35:59 WARN]:        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.
    java:2620)
    [21:35:59 WARN]:        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.
    java:2570)
    [21:35:59 WARN]:        at com.mysql.jdbc.StatementImpl.executeQuery(StatementIm
    pl.java:1474)
    [21:35:59 WARN]:        at me.pvpdog.sqlproject.commands.AddCommand.onCommand(Ad
    dCommand.java:64)
    [21:35:59 WARN]:        at org.bukkit.command.PluginCommand.execute(PluginComman
    d.java:44)
    [21:35:59 WARN]:        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCo
    mmandMap.java:141)
    [21:35:59 WARN]:        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCo
    mmand(CraftServer.java:640)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.PlayerConnection.handleC
    ommand(PlayerConnection.java:1162)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.PlayerConnection.a(Playe
    rConnection.java:997)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(Packe
    tPlayInChat.java:45)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(Packe
    tPlayInChat.java:1)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.
    run(SourceFile:13)
    [21:35:59 WARN]:        at java.util.concurrent.Executors$RunnableAdapter.call(U
    nknown Source)
    [21:35:59 WARN]:        at java.util.concurrent.FutureTask.run(Unknown Source)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.SystemUtils.a(SystemUtil
    s.java:19)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.B(Minecr
    aftServer.java:714)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.DedicatedServer.B(Dedica
    tedServer.java:374)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.A(Minecr
    aftServer.java:653)
    [21:35:59 WARN]:        at net.minecraft.server.v1_8_R3.MinecraftServer.run(Mine
    craftServer.java:556)
    [21:35:59 WARN]:        at java.lang.Thread.run(Unknown Source)
    On
    Code:
    try {
                        ResultSet res = statement.executeQuery("SELECT * FROM players WHERE email = "+args[1].toLowerCase());
                        res.next();
    
                        if(res.getString("email")==null){
                            p.sendMessage(ChatColor.GREEN+"You have not registered!");
                            return true;
                        }else{
                            p.sendMessage(ChatColor.RED+"You have already registered your email!");
                            return false;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                        return false;
                    }
    Plz help.
     
  24. Offline

    Xerox262

    You have to actually connect to the database first.
     
  25. Offline

    DoggyCode™

    I do have a connection.
     
  26. Offline

    FiesteroCraft

    In c = MySQL.openConnection(); i have to add that in my onEnable() with try/catch ?
     
  27. Offline

    CeramicTitan

    Probably, your IDE will tell you
     
  28. Offline

    A_Brave_Panda

    Could anyone help me please? Im getting this error:

    Code:
    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    [13:06:42 WARN]:        at sun.reflect.GeneratedConstructorAccessor226.newInstance(Unknown Source)
    [13:06:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    [13:06:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Unknown Source)
    [13:06:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    [13:06:42 WARN]:        at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
    [13:06:42 WARN]:        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
    [13:06:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251)
    [13:06:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
    [13:06:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
    [13:06:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
    [13:06:42 WARN]:        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    [13:06:42 WARN]:        at sun.reflect.GeneratedConstructorAccessor223.newInstance(Unknown Source)
    [13:06:42 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    [13:06:42 WARN]:        at java.lang.reflect.Constructor.newInstance(Unknown Source)
    [13:06:42 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    [13:06:42 WARN]:        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
    [13:06:42 WARN]:        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
    [13:06:42 WARN]:        at java.sql.DriverManager.getConnection(Unknown Source)
    [13:06:42 WARN]:        at java.sql.DriverManager.getConnection(Unknown Source)
    [13:06:42 WARN]:        at me.zachbears27.MySQL.openConnection(MySQL.java:77)
    [13:06:42 WARN]:        at me.zachbears27.DeathLocation.onEnable(DeathLocation.java:32)
    [13:06:42 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:271)
    [13:06:42 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
    [13:06:42 WARN]:        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405)
    [13:06:42 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.CraftServer.enablePlugin(CraftServer.java:375)
    [13:06:42 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.CraftServer.enablePlugins(CraftServer.java:325)
    [13:06:42 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.CraftServer.reload(CraftServer.java:749)
    [13:06:42 WARN]:        at org.bukkit.Bukkit.reload(Bukkit.java:540)
    [13:06:42 WARN]:        at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:25)
    [13:06:42 WARN]:        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141)
    [13:06:42 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.CraftServer.dispatchCommand(CraftServer.java:649)
    [13:06:42 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.CraftServer.dispatchServerCommand(CraftServer.java:635)
    [13:06:42 WARN]:        at net.minecraft.server.v1_11_R1.DedicatedServer.aM(DedicatedServer.java:437)
    [13:06:42 WARN]:        at net.minecraft.server.v1_11_R1.DedicatedServer.D(DedicatedServer.java:400)
    [13:06:42 WARN]:        at net.minecraft.server.v1_11_R1.MinecraftServer.C(MinecraftServer.java:675)
    [13:06:42 WARN]:        at net.minecraft.server.v1_11_R1.MinecraftServer.run(MinecraftServer.java:574)
    [13:06:42 WARN]:        at java.lang.Thread.run(Unknown Source)
    [13:06:42 WARN]: Caused by: java.net.ConnectException: Connection refused: connect
    [13:06:42 WARN]:        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    [13:06:42 WARN]:        at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    [13:06:42 WARN]:        at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    [13:06:42 WARN]:        at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    [13:06:42 WARN]:        at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    [13:06:42 WARN]:        at java.net.PlainSocketImpl.connect(Unknown Source)
    [13:06:42 WARN]:        at java.net.SocksSocketImpl.connect(Unknown Source)
    [13:06:42 WARN]:        at java.net.Socket.connect(Unknown Source)
    [13:06:42 WARN]:        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
    [13:06:42 WARN]:        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
    [13:06:42 WARN]:        ... 31 more
    Code:

    Code:
    package me.zachbears27;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.PlayerDeathEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    import me.zachbears27.MySQL;
    
    public class DeathLocation extends JavaPlugin implements Listener {
        DeathLocation plugin;
    
        MySQL MySQL = new MySQL("localhost", "3306", "id115504_mumbo", "STUFF", "STUFF");
           Connection connection = null;
    
    
    @Override
    public void onDisable() {
    
    }
    
    @Override
    public void onEnable() {
    
      getServer().getPluginManager().registerEvents(this, this);
      try {
        connection = MySQL.openConnection();
        Bukkit.broadcastMessage("uau");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
    
        e.printStackTrace();
    }
    
    }
    
    @EventHandler
    public void onPlayerDeath(PlayerDeathEvent e) {
      if (e.getEntity() instanceof Player) {
       Player p = e.getEntity();
       Location loc = e.getEntity().getLocation();
       int x = loc.getBlockX();
       int y = loc.getBlockY();
       int z = loc.getBlockZ();
       String time = "its time";
       Bukkit.broadcastMessage(x + " " + y + " " + z );
       String statementstring = "INSERT INTO `" + "id115504_mumbo" + "`DeathLocations` (`PlayerName`, `X`, `Y`, `Z`, `Time`) VALUES (" + p.getName() + ", '" + x + "', '" + y + "', '" + z + "', '" + time + "');";
       try {
        Statement statement = this.connection.createStatement();
        statement.executeUpdate(statementstring);
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    }
    }
    
    }
     
  29. Offline

    z0ckyZockt

    Hey guys,

    I have a problem.

    These is my code:
    Code:
    package Main;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import MySQL.MySQL;
    
    public class one extends JavaPlugin{
       
       
        MySQL MySQL = new MySQL(plugin, "**********", "3306", "LoginSecurity", "********", "**********");
        Connection c = null;
       
        @Override
        public void onEnable() {
           
            c = MySQL.openConnection();
           
        }
       
        Statement statement = c.createStatement();
       
        public void OnJoin(PlayerJoinEvent e){
            Statement statement = c.createStatement();
            ResultSet res = statement.executeQuery("SELECT * FROM users WHERE UUID = '" + e.getPlayer().getUniqueId().toString() + "';");
            res.next();
           
            if(res.getString("UUID") == null){
                statement.executeQuery("INSERT INTO users (`id`, `UUID`) VALUES (`null`, `"+ e.getPlayer().getUniqueId().toString() +"`);");
                e.getPlayer().sendMessage("/register <passwort>");
               
            }
        }
       
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            Player p = (Player) p;
           
            if(cmd.getName().equalsIgnoreCase("register")){
                ResultSet res1 = statement.executeQuery("SELECT password FROM users WHERE UUID = '" + p.getUniqueId().toString() + "';");
                if(res1.getString("password") == null){
                    if(args.length == 0){
                        p.sendMessage("/register <password>");
                    } else if(args.length == 1){
                        String pw = args[0];
                        statement.executeQuery("UPDATE `users` set `password` = '"+ pw +"' WHERE UUID = " + p.getUniqueId().toString() + ";");
                        p.sendMessage("Du hast dich erfolgreich registriert!");
                        p.sendMessage("/email <email>");
                    }
                } else {
                    p.sendMessage("Du hast dich schon Registriert! (/login <password>)");
                }
               
                return true;
            }
           
            if(cmd.getName().equalsIgnoreCase("email")){
                ResultSet res2 = statement.executeQuery("SELECT email FROM users WHERE UUID = '" + p.getUniqueId().toString() + "';");
                if(res2.getString("email") == null){
                    if(args.length == 0){
                        p.sendMessage("/email <email>");
                    } else if(args.length == 1){
                        String email = args[0];
                        statement.executeQuery("UPDATE `users` set `email` = '"+ email +"' WHERE UUID = " + p.getUniqueId().toString() + ";");
                        p.sendMessage("Du hast deine Email-Adresse erfolgreich hinterlegt!");
                    }
                } else {
                    p.sendMessage("Du hast schon eine Email-Adresse hinterlegt!");
                }
                return true;
            }
           
           
            return false;
        }
       
        @Override
        public void onDisable() {
           
            MySQL.closeConnection();
           
        }
       
       
       
    }
    
    I have an error on line 18.

    Line 18:
    Code:
     MySQL MySQL = new MySQL(plugin, "*********", "3306", "LoginSecurity", "*******", "*******"); 
    The error ist plugin but i don't know to fix it.
    Can anyone help me?

    Sorry for my bad english.
     
  30. Offline

    timtower Administrator Administrator Moderator

Thread Status:
Not open for further replies.

Share This Page