MySQL connection

Discussion in 'Plugin Help/Development/Requests' started by tylerthecreeper1, Mar 24, 2015.

Thread Status:
Not open for further replies.
  1. Hello, I'm having trouble connecting to my database with MySQL. I haven't worked much with databases, and a friend gave me this code, and my plugin is not connecting to the database, not sure why.

    Code:
    public class DatabaseConnection
    {
      public Connection con;
      private String address;
      private String database;
      private String port;
      private String username;
      private String password;
      private String logName;
      public DatabaseConnection(String address, String database, String port, String username, String password, String logName)
      {
        this.address = TylerServer.getInstance().getConfig().getString("MySQL.address");
        this.database = TylerServer.getInstance().getConfig().getString("MySQL.database");
        this.port = TylerServer.getInstance().getConfig().getString("MySQL.port");
        this.username = TylerServer.getInstance().getConfig().getString("MySQL.username");
        this.password = TylerServer.getInstance().getConfig().getString("MySQL.password");
        this.logName = logName;
      }
      public Connection getConnection()
        throws SQLException, ClassNotFoundException
      {
        String prefix = "[" + this.logName + "] ";
        try
        {
          Class.forName("com.mysql.jdbc.Driver");
          if ((this.con == null) || (this.con.isClosed())) {
            this.con = DriverManager.getConnection("jdbc:mysql://" + this.address + ":" + this.port + "/" + this.database, this.username, this.password);
          }
          System.out.println(prefix + "MySQL connection successful.");
        }
        catch (SQLException e)
        {
          System.out.println(prefix + "MySQL connection failed.");
          return null;
        }
        catch (ClassNotFoundException e)
        {
          System.out.println(prefix + "MySQL connection failed.");
          return null;
        }
        return this.con;
      }
    
    Any help ASAP would be greatly appreciated!
     
  2. Offline

    mythbusterma

    @tylerthecreeper1

    So uh....let's go down the list:

    1. The code isn't formatted correctly and is therefore difficult to read
    2. Why is "con" a public field?
    3. "Prefix" should be static and final
    4. Why does that method throw ClassNotFoundException and SQLException when it can never throw them?
    5. The code would probably print something to the console when it fails to connect, that can tell us why it's not connecting
     
  3. Offline

    DemKazoo

    @mythbusterma To be honest, the code actually is well formated.
     
  4. Offline

    nverdier

    Are you referring to the Allman style? Most people actually use that over K&R, and it's much more legible than the latter.
     
  5. Offline

    1Rogue Retired Staff

    Yeah... allman

    As for "more readable", that's entirely opinion based, but by convention Java does not use allman.


    Print out your errors and the SQLException error code, don't just say there's an error as that doesn't help you fix your plugin at all
     
  6. Offline

    nverdier

  7. @1Rogue Error code.
    Code:
    [14:02:49 INFO]: [TylerServer] Enabling TylerServer v1.0
    [14:02:49 INFO]: [TylerServer] MySQL connection failed.
    [14:02:49 ERROR]: Error occurred while enabling TylerServer v1.0 (Is it up to da
    te?)
    java.lang.NullPointerException
            at org.nocturnalgaming.tylerserver.database.DatabaseManager.checkDatabas
    e(DatabaseManager.java:25) ~[?:?]
            at org.nocturnalgaming.tylerserver.TylerServer.onEnable(TylerServer.java
    :27) ~[?:?]
            at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[s
    pigot.jar:git-Spigot-6ee12f6-33d5de3]
            at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
    .java:335) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
    r.java:405) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at org.bukkit.craftbukkit.v1_8_R1.CraftServer.loadPlugin(CraftServer.jav
    a:356) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at org.bukkit.craftbukkit.v1_8_R1.CraftServer.enablePlugins(CraftServer.
    java:316) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at net.minecraft.server.v1_8_R1.MinecraftServer.q(MinecraftServer.java:4
    02) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at net.minecraft.server.v1_8_R1.MinecraftServer.k(MinecraftServer.java:3
    70) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at net.minecraft.server.v1_8_R1.MinecraftServer.a(MinecraftServer.java:3
    25) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at net.minecraft.server.v1_8_R1.DedicatedServer.init(DedicatedServer.jav
    a:211) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at net.minecraft.server.v1_8_R1.MinecraftServer.run(MinecraftServer.java
    :505) [spigot.jar:git-Spigot-6ee12f6-33d5de3]
            at java.lang.Thread.run(Unknown Source) [?:1.7.0_75]
    
    DatabaseManager.java :

    Code:
    package org.nocturnalgaming.tylerserver.database;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.UUID;
    
    import org.nocturnalgaming.tylerserver.TylerServer;
    
    public class DatabaseManager
    {
      private DatabaseConnection Query = new DatabaseConnection(TylerServer.getInstance().getConfig().getString("MySQL.Address"), TylerServer.getInstance().getConfig().getString("MySQL.Database"), TylerServer.getInstance().getConfig().getString("MySQL.Port"), TylerServer.getInstance().getConfig().getString("MySQL.Username"), TylerServer.getInstance().getConfig().getString("MySQL.Password"), TylerServer.getInstance().getDescription().getName());
      private static DatabaseManager instance = new DatabaseManager();
      public static DatabaseManager getInstance()
      {
        return instance;
      }
      public void checkDatabase()
      {
        try
        {
          Connection con = this.Query.getConnection();
          con.createStatement().execute("CREATE TABLE IF NOT EXISTS moonData (uuid VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci, username VARCHAR(30) CHARACTER SET utf8 COLLATE utf8_general_ci, moons INTEGER) CHARACTER SET utf8 COLLATE utf8_general_ci");
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public void enterNewPlayer(UUID uuid, String name)
      {
        try
        {
          this.Query.getStatement().execute("INSERT INTO moonData (uuid, username, moons) VALUES('" + uuid.toString() + "', '" + name + "', 0)");
          //this.Query.getStatement().execute("INSERT INTO banData (uuid, username, length) VALUES('" + uuid.toString() + "', '" + name + "', "')");
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public void setNameOfPlayer(UUID uuid, String name)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT username FROM moonData WHERE uuid='" + uuid.toString() + "';");
          if (rs.next()) {
            this.Query.getStatement().execute("UPDATE moonData SET username='" + name + "' WHERE uuid='" + uuid.toString() + "';");
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public boolean doesPlayerExist(String name)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT * FROM moonData WHERE username='" + name + "';");
          boolean doesContainPlayer = rs.next();
         
          @SuppressWarnings("unused")
        boolean bool1 = doesContainPlayer;
         
    
    
    
    
    
    
          return false;
        }
        catch (SQLException e)
        {
          e.printStackTrace();
          return false;
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
            return false;
        }
        finally {}
        //return false;
      }
      public boolean doesPlayerExist(UUID uuid)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT * FROM moonData WHERE uuid='" + uuid.toString() + "';");
          return rs.next();
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
        return false;
      }
      public void giveMoons(UUID uuid, int amount)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE uuid='" + uuid.toString() + "';");
          if (rs.next()) {
            this.Query.getStatement().execute("UPDATE moonData SET moons=" + Integer.toString(getMoons(uuid) + amount) + " WHERE uuid='" + uuid.toString() + "';");
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public int getMoons(UUID uuid)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE uuid='" + uuid.toString() + "';");
          if (rs.next()) {
            return rs.getInt(1);
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
        return 0;
      }
      public int getMoons(String name)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE username='" + name + "';");
          if (rs.next()) {
            return rs.getInt(1);
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
        return 0;
      }
      public void setMoons(String name, int amount)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE username='" + name + "';");
          if (rs.next()) {
            this.Query.getStatement().execute("UPDATE moonData SET moons=" + Integer.toString(amount) + " WHERE username='" + name + "';");
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public void setMoons(UUID uuid, int amount)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE uuid='" + uuid.toString() + "';");
          if (rs.next()) {
            this.Query.getStatement().execute("UPDATE moonData SET moons=" + Integer.toString(amount) + " WHERE uuid='" + uuid.toString() + "';");
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
      public void removeMoons(UUID uuid, int amount)
      {
        try
        {
          ResultSet rs = this.Query.getStatement().executeQuery("SELECT moons FROM moonData WHERE uuid='" + uuid.toString() + "';");
          if (rs.next()) {
            this.Query.getStatement().execute("UPDATE moonData SET moons=" + Integer.toString(getMoons(uuid) - amount) + " WHERE uuid='" + uuid.toString() + "';");
          }
        }
        catch (SQLException e)
        {
          e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
        }
      }
    }
    
     
  8. Offline

    1Rogue Retired Staff

    Yes, but that doesn't change language conventions. Java is not allman (that's more predominately C++/C#). Additionally the code posted is not allman, it doesn't follow any convention because it mixes multiple styles (and thus, not formatted correctly).

    Query is null, also your singleton pattern is incorrect (you can still create multiple instances of DatabaseManager (which I assume is also linked to the problem).
     
  9. @1Rogue Shouldn't be null, it reads from the config, and the config has the info in it.
     
  10. Offline

    1Rogue Retired Staff

    Query is the only DI member in the checkDatabase method which is dereferenced. No other variable will cause a NullPointerException (assuming the Connection object is from jdbc).
     
Thread Status:
Not open for further replies.

Share This Page