Tutorial Using MySQL In your Plugins!

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

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

    -_Husky_-

  2. Offline

    x128

    -_Husky_-

    public class Main extends JavaPlugin implements Listener{
    MySQL MySQL = new MySQL("host.name", 12345, "user", "pass");

    Connection c = null;


    "The constructor MySQL(String, int, String, String) is undefined"
     
  3. Offline

    tips48

    Are you using the new version from Github? Or the old one
     
  4. Offline

    x128

    tips48
    I am getting tons of errors in the MySQL file, and when I try to add it to my own code.

    MySQL.java errors:
    Code:java
    1. public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) {
    2. super(plugin);
    3. this.hostname = hostname;
    4. }

    Code:
    The constructor Database(Plugin) is undefined
    Code:java
    1. @Override
    2. public Connection openConnection() {
    3. try {
    4. Class.forName("com.mysql.JDBC.Driver");
    5. connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password);
    6. } catch (SQLException e) {
    7. plugin.getLogger().log(Level.SEVERE, "Could not connect to MySQL server! because: " + e.getMessage());
    8. } catch (ClassNotFoundException e) {
    9. plugin.getLogger().log(Level.SEVERE, "JDBC Driver not found!");
    10. }
    11. return connection;
    12. }

    Code:
    OpenConnection():
    The method openConnection() of type MySQL must override or implement a supertype method
     
    plugin cannot be resolved
    
    Code:java
    1. @Override
    2. public boolean checkConnection() {
    3. return connection != null;
    4. }

    Code:
    The method checkConnection() of type MySQL must override or implement a supertype method
    Code:java
    1. @Override
    2. public Connection getConnection() {
    3. return connection;
    4. }

    Code:
    The method getConnection() of type MySQL must override or implement a supertype method
    Code:java
    1. @Override
    2. public void closeConnection() {
    3. if (connection != null) {
    4. try {
    5. connection.close();
    6. } catch (SQLException e) {
    7. plugin.getLogger().log(Level.SEVERE, "Error closing the MySQL Connection!");
    8. e.printStackTrace();
    9. }
    10. }

    Code:
    The method closeConnection() of type MySQL must override or implement a supertype method
     
    Also on plugin.getLogger()
    On top of all of this, when I try to connect to MySQL in my main:
    Code:
    The constructor MySQL(String, int, String, String) is undefined
    :'(
     
  5. Offline

    gomeow

    x128
    When you updated your code, did you update all of it, or just the MySQL.java class
     
  6. Offline

    Mang0eZPvP

    Just Asking How Would i read a string and send it to the player?
     
  7. Offline

    Mang0eZPvP

    Help Me Here: http://forums.bukkit.org/threads/how-do-i-show-an-string-from-mysql-to-bukkkit.166774/

    This is Something i need help with!

    Here Is The Code:


    Code:java
    1. try {
    2. p.setPlayerListName(settings.getRank().getString("groups." + st.executeQuery("SELECT rank FROM players WHERE rank='owner';") + ".chat").replace("&", "§") + p.getName() + "" + ChatColor.RESET);
    3. } catch (SQLException e) {
    4.  
    5. e.printStackTrace();
    6. }


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

    gomeow

    Mang0eZPvP
    executeQuery returns a ResultSet, not a String
     
  9. Offline

    Skyshayde

    Assuming the ResultSet is a single row, you can run getString(ColumnName/Index) on it for the string. If not, I believe you move down with next() on a ResultSet.
     
  10. Offline

    Mang0eZPvP

    yea tryed dat. it has to match a certain string though
     
  11. Offline

    GaaTavares

    I'm having a problem:

    Code:java
    1. me.iroxy.shared.mysql.MySQL MySQL = new me.iroxy.shared.mysql.MySQL("host.name", "aaa", "aaa", "user", "pass");
    2. Connection c = null;


    I'm getting an error: the constructor MYSQL(String, String, String, String, String) is undefined o.o

    What is wrong?
     
  12. Offline

    Mang0eZPvP


    Really Need The Help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! PLS......

    Here Is The Stack Trace:

    Code:
    16:15:43 [SEVERE] java.sql.SQLException: Before start of result set
    16:15:43 [SEVERE]      at com.mysql.jdbc.SQLError.createSQLException(SQLError.j
    ava:1073)
    16:15:43 [SEVERE]      at com.mysql.jdbc.SQLError.createSQLException(SQLError.j
    ava:987)
    16:15:43 [SEVERE]      at com.mysql.jdbc.SQLError.createSQLException(SQLError.j
    ava:982)
    16:15:43 [SEVERE]      at com.mysql.jdbc.SQLError.createSQLException(SQLError.j
    ava:927)
    16:15:43 [SEVERE]      at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImp
    l.java:841)
    16:15:43 [SEVERE]      at com.mysql.jdbc.ResultSetImpl.getStringInternal(Result
    SetImpl.java:5656)
    16:15:43 [SEVERE]      at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.
    java:5576)
    16:15:43 [SEVERE]      at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.
    java:5616)
    16:15:43 [SEVERE]      at com.fruitspvp.Main.onEnable(Main.java:41)
    16:15:43 [SEVERE]      at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlug
    in.java:217)
    16:15:43 [SEVERE]      at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(
    JavaPluginLoader.java:457)
    16:15:43 [SEVERE]      at org.bukkit.plugin.SimplePluginManager.enablePlugin(Si
    mplePluginManager.java:381)
    16:15:43 [SEVERE]      at org.bukkit.craftbukkit.v1_6_R2.CraftServer.loadPlugin
    (CraftServer.java:282)
    16:15:43 [SEVERE]      at org.bukkit.craftbukkit.v1_6_R2.CraftServer.enablePlug
    ins(CraftServer.java:264)
    16:15:43 [SEVERE]      at org.bukkit.craftbukkit.v1_6_R2.CraftServer.reload(Cra
    ftServer.java:605)
    16:15:43 [SEVERE]      at org.bukkit.Bukkit.reload(Bukkit.java:275)
    16:15:43 [SEVERE]      at org.bukkit.command.defaults.ReloadCommand.execute(Rel
    oadCommand.java:23)
    16:15:43 [SEVERE]      at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCo
    mmandMap.java:189)
    16:15:43 [SEVERE]      at org.bukkit.craftbukkit.v1_6_R2.CraftServer.dispatchCo
    mmand(CraftServer.java:523)
    16:15:43 [SEVERE]      at org.bukkit.craftbukkit.v1_6_R2.CraftServer.dispatchSe
    rverCommand(CraftServer.java:512)
    16:15:43 [SEVERE]      at net.minecraft.server.v1_6_R2.DedicatedServer.ar(Dedic
    atedServer.java:262)
    16:15:43 [SEVERE]      at net.minecraft.server.v1_6_R2.DedicatedServer.t(Dedica
    tedServer.java:227)
    16:15:43 [SEVERE]      at net.minecraft.server.v1_6_R2.MinecraftServer.s(Minecr
    aftServer.java:486)
    16:15:43 [SEVERE]      at net.minecraft.server.v1_6_R2.MinecraftServer.run(Mine
    craftServer.java:419)
    16:15:43 [SEVERE]      at net.minecraft.server.v1_6_R2.ThreadServerApplication.
    run(SourceFile:582)

    And Here Is The Code:

    Code:java
    1. public void onEnable() {
    2. c = MySQL.open();
    3. Bukkit.getServer().getPluginManager().registerEvents(this, this);
    4.  
    5. try {
    6. final Statement s = MySQL.open().createStatement();
    7. for (Player p : Bukkit.getOnlinePlayers()) {
    8. try {
    9. p.setPlayerListName(settings.getRank().getString(s.executeQuery("SELECT rank FROM players WHERE plName= '" + p.getName() + "';") + ".chat").replace("&", "§") + p.getName() + "" + ChatColor.RESET);
    10. } catch (SQLException e) {
    11. e.printStackTrace();
    12. }
    13. }
    14. } catch (SQLException e1) {
    15. e1.printStackTrace();
    16. }
    17.  
    18.  
    19. }


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

    Mang0eZPvP

    -_Husky_- Can You Help Me!!!!!!!!!!!!!!!!!! Pls look at previous post
     
  14. Offline

    gomeow

  15. Offline

    tips48

    Hey guys, sorry about the wait on a new tutorial. School starts on thursday and it's important that I have everything ready. Assuming everything goes well I should have a tutorial out soon
     
  16. Offline

    Mang0eZPvP

  17. Offline

    Virgoth098

    Let's say I have a table named 'Tokens' in a database named ''
    It would be a simple table that stores a player's name, and the amount of tokens that the player has. Would this be correct?
    Code:java
    1. try
    2. {
    3. statement = connection.createStatement();
    4. statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + tokens + " (Username VARCHAR(20), Tokens int(20));");
    5. plugin.getLogger().info("Database Table Has Been Created");
    6. } catch (SQLException e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }

    And another question, if I want to get data from that table, how would the executeQuery look? I have this so far...
    Code:java
    1. ResultSet res = statement.executeQuery("SELECT * FROM " + plugin.database + "WHERE tokens = '" + name + "';");

    But I don't know what else to do in that. I don't have a name variable, would it just be the username that is stored in the database?
     
  18. Offline

    tips48

  19. Offline

    Mang0eZPvP

    ok nvm i fixed it

    using this:

    Code:java
    1. public String getString(String item, String table, String where, String whereClause) throws Exception {
    2. Statement s = EnableMain.getInstance().MySQL.open().createStatement();
    3. ResultSet rs = s.executeQuery("SELECT " + item + " FROM " + table + " WHERE " + where + "=('" + whereClause + "');");
    4. rs.next();
    5. return rs.getString(1);
    6. }
     
  20. Offline

    Jombi

    Whenever my code is triggered, I get this in the console:
    Code:
    JDBC Driver not found!
    
    But I can't figure out why the JDBC driver isn't in my classpath. Doesn't it come with Bukkit/Spigot?
    Any help is appreciated.
     
  21. Offline

    creatorfromhell

    Just a few suggestions for the tutorial..
    Next, in your main class, add
    Code:java
    1. MySQL MySQL = new MySQL("host.name", port, "user", "pass");
    2. Connection c = null;


    Should be as below, because if you name it the same as your class name then you're going to run into trouble. Also, you don't need to make an instance of connection, because that's what getConn() is for.
    Code:java
    1. MySQL sql = new MySQL("host.name", port, "user", "pass");


    Import the connection from java.sql.Connection

    Now all you need to do is open the connection,

    in onEnable(), add
    Code:java
    1. c = MySQL.open();


    Should be as below, because you don't need to make another instance of Connection since one already exists in the MySQL class.

    Code:java
    1. sql.open();
     
  22. Offline

    Mang0eZPvP

    Help me pls:

    StackTrace
    Code:
    09:56:25 [INFO] ManG0eZPvP[/127.0.0.1:50860] logged in with entity id 1190 at ([
    world] 2.677228093074679, 4.0, 10.470576986790093)
    09:56:25 [SEVERE] Could not pass event PlayerJoinEvent to Squeez v1.0
    org.bukkit.event.EventException
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
    va:427)
            at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.jav
    a:62)
            at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.j
    ava:477)
            at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.j
    ava:462)
            at net.minecraft.server.v1_6_R2.PlayerList.c(PlayerList.java:206)
            at net.minecraft.server.v1_6_R2.PlayerList.a(PlayerList.java:102)
            at net.minecraft.server.v1_6_R2.PendingConnection.e(PendingConnection.ja
    va:130)
            at net.minecraft.server.v1_6_R2.PendingConnection.d(PendingConnection.ja
    va:43)
            at net.minecraft.server.v1_6_R2.DedicatedServerConnectionThread.a(Dedica
    tedServerConnectionThread.java:41)
            at net.minecraft.server.v1_6_R2.DedicatedServerConnection.b(SourceFile:2
    9)
            at net.minecraft.server.v1_6_R2.MinecraftServer.t(MinecraftServer.java:5
    90)
            at net.minecraft.server.v1_6_R2.DedicatedServer.t(DedicatedServer.java:2
    26)
            at net.minecraft.server.v1_6_R2.MinecraftServer.s(MinecraftServer.java:4
    86)
            at net.minecraft.server.v1_6_R2.MinecraftServer.run(MinecraftServer.java
    :419)
            at net.minecraft.server.v1_6_R2.ThreadServerApplication.run(SourceFile:5
    82)
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown co
    lumn 'ManG0eZPvP' in 'field list'
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
     
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
    rce)
            at java.lang.reflect.Constructor.newInstance(Unknown Source)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
            at com.mysql.jdbc.Util.getInstance(Util.java:382)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3593)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3525)
            at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986)
            at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2140)
            at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2620)
            at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1662)
            at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1581)
            at com.fruitspvp.MySQLCmds.setGroup(MySQLCmds.java:49)
            at com.fruitspvp.listeners.PlayerJoin.onPlayerLogin(PlayerJoin.java:150)
     
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
    va:425)
            ... 14 more

    Code Login Class:

    Code:java
    1. if (mc.isNull("plName", "players", "plName")) {
    2. p.sendMessage("Null");
    3. mc.setGroup("players", p.getName(), "default", "0");
    4. }



    Code Sytax where error occurs :

    Code:java
    1. public void setGroup(String table, String player, String items, String coins) throws Exception {
    2. Statement s = EnableMain.getInstance().MySQL.open().createStatement();
    3. s.executeUpdate("INSERT INTO " + table + "(plName,rank,coins) VALUES(" + player + "," + items + "," + coins + ");");
    4. }


    Thanks In Future For Your Help
     
  23. Offline

    creatorfromhell


    This may not help but try replacing this:
    Code:java
    1. s.executeUpdate("INSERT INTO " + table + "(plName,rank,coins) VALUES(" + player + "," + items + "," + coins + ");");


    with this:
    Code:java
    1. s.executeUpdate("INSERT INTO " + table + "(`plName`, `rank`, `coins`) VALUES ('" + player + "', '" + items + "','" + coins + "');");
     
    -_Husky_- likes this.
  24. Offline

    Mang0eZPvP

    thnks it worked :D
     
  25. Offline

    creatorfromhell

    You're welcome.
     
    -_Husky_- likes this.
  26. Offline

    frogawesome

    i get this error log every time i do my command:
    Code:
    org.bukkit.command.CommandException: Unhandled exception executing command 'frogcoins' in plugin DvZPoints v1.0
    at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46)
    at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:189)
    at org.bukkit.craftbukkit.v1_6_R2.CraftServer.dispatchCommand(CraftServer.java:523)
    at net.minecraft.server.v1_6_R2.PlayerConnection.handleCommand(PlayerConnection.java:964)
    at net.minecraft.server.v1_6_R2.PlayerConnection.chat(PlayerConnection.java:882)
    at net.minecraft.server.v1_6_R2.PlayerConnection.a(PlayerConnection.java:839)
    at net.minecraft.server.v1_6_R2.Packet3Chat.handle(SourceFile:49)
    at net.minecraft.server.v1_6_R2.NetworkManager.b(NetworkManager.java:296)
    at net.minecraft.server.v1_6_R2.PlayerConnection.e(PlayerConnection.java:118)
    at net.minecraft.server.v1_6_R2.ServerConnection.b(SourceFile:37)
    at net.minecraft.server.v1_6_R2.DedicatedServerConnection.b(SourceFile:30)
    at net.minecraft.server.v1_6_R2.MinecraftServer.t(MinecraftServer.java:590)
    at net.minecraft.server.v1_6_R2.DedicatedServer.t(DedicatedServer.java:226)
    at net.minecraft.server.v1_6_R2.MinecraftServer.s(MinecraftServer.java:486)
    at net.minecraft.server.v1_6_R2.MinecraftServer.run(MinecraftServer.java:419)
    at net.minecraft.server.v1_6_R2.ThreadServerApplication.run(SourceFile:582)
    Caused by: java.lang.NullPointerException
    at me.frogawesome.DvZPoints.DvZPointsMain.onCommand(DvZPointsMain.java:40)
    at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)
    ... 15 more
    and this is my code
    MySQL sql = new MySQL(this, "localhost", "3306", "mcd_76", "mcd_76", "3d4bb4102f");

    inttokens = 0;


    @Override

    publicvoid onEnable() {

    sql.openConnection();

    System.out.println("Enabled");


    }



    @Override

    publicvoid onDisable() {

    // TODO Auto-generated method stub

    super.onDisable();


    }



     

    publicboolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){

    if(cmd.getName().equalsIgnoreCase("frogcoins")){


    Player player = (Player) sender;

    try {

    Statement s = sql.openConnection().createStatement();

    ResultSet res = s.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + player.getName() + "';");


    res.next();

    if(res.getString("PlayerName") == null) {


    tokens = 0;


    } else {


    tokens = res.getInt("tokens");

    player.sendMessage(tokens+"");




    }

    s.executeUpdate("INSERT INTO mcd_76 (`plName`, `coins`) VALUES ('" + player.getName() + "','" + args[0] + "');");

    System.out.println("Inserted info");




     

     

     

    } catch (SQLException e) {

    // TODO Auto-generated catch block


    e.printStackTrace();

    }



    }

    returnfalse;


    }

    }
     
  27. Offline

    Mang0eZPvP

    Line
    line 40. Were is it???
     
  28. Offline

    frogawesome

    i fixd it the problem whas that i whas not checking if it had a connection.
     
  29. Offline

    lycano

    -_Husky_- it would be nice if you could add ConnectionPool into your implementation.
     
    hawkfalcon likes this.
  30. Offline

    Dad_Yoshi

    Consider this a 'Best Practice'
    If you are using database tables you should always give them some sort of name prefix.

    So instead of having your tables being named 'entities', 'actions', and 'worlds' you would use 'dy_entities', 'dy_actions', and 'dy_worlds' (I chose 'dy' for Dad_Yoshi). This allows for situations where another plugin used the same simple table names you thought of but didn't give them a prefix. It also allows those server admins who know their way around SQL to see at a glance which tables relate to your plugin.:D
     
Thread Status:
Not open for further replies.

Share This Page