Tutorial Using MySQL In your Plugins!

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

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

    nopresnik

    -_Husky_-

    Doesn't seem like there is a method named open()

    My IDE is asking for me to create it.

    EDIT:
    I tried Statement s = plugin.MySQL.openConnection().createStatement(); and I get the exact same stacktrace.

    Thanks.
     
    mba2012 likes this.
  2. Offline

    -_Husky_-

    Ohhh. I now know why.

    I'll reply when I get on a computer.
     
    mba2012 likes this.
  3. Offline

    nopresnik

    Awesome, thank you.
     
  4. Offline

    masj2

    I cant get it to work, the class MySQL apperently doesnt excist.
    Code:
    package me.masj2.Basics;
     
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.logging.Logger;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Location;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Basics extends JavaPlugin{
     
        public final Logger logger = Logger.getLogger("Minecraft");
        public static Basics plugin;
      [COLOR=#ff0000] MySQL[/COLOR] MySQL = new [COLOR=#ff0000]MySQL[/COLOR](plugin, "192.168.0.101", "3306", "minecraft","root","password");
        Connection c =null;
     
        @Override
        public void onDisable(){
            PluginDescriptionFile pdfFile = this.getDescription();
            this.logger.info(pdfFile.getName() + " Has Been Disabled.");
        }
        @Override
        public void onEnable(){
            PluginDescriptionFile pdfFile = this.getDescription();
            c = [COLOR=#ff0000]MySQL[/COLOR].openConnection();
            this.logger.info(pdfFile.getName() + " Vesion " + pdfFile.getVersion() + " Has Been Enabled.");
        }
     
        public boolean onCommand(CommandSender sender, Command cmd, String commandLable, String[] args){
            Player player = (Player) sender;
            if(commandLable.equalsIgnoreCase("sethome")){
                Location loc = player.getLocation();
                double x = loc.getX();
                double y = loc.getY();
                double z = loc.getZ();
                Statement statement = c.createStatement();
                statement.executeQuery("INSERT INTO users (`ign`, `x`, `y`, `z`) VALUES ('" + player + "', '" + x + "', '" + y + "', '" + z + "');");
                player.sendMessage(ChatColor.GREEN + "Your home has been set to this place.");
                return false;
            }
            if(commandLable.equalsIgnoreCase("home")){
                player.sendMessage(toString());
                Statement statement = c.createStatement();
                ResultSet res = statement.executeQuery("SELECT * FROM users WHERE ign = '" + player + "';");
                res.next();
                if(res.getString("ign") == null) {
                    player.sendMessage(ChatColor.RED + "You have not set any home yet. Use /sethome");
                    } else {
                    double x = res.getInt("x");
                    double y = res.getInt("y");
                    double z = res.getInt("z");
                    Location loc = player.getLocation();
                    loc.setX(x);
                    loc.setY(y);
                    loc.setZ(z);
                    player.teleport(loc);
                    }
                return false;
            }
        }
    }
    
    I have included all 3 files in the same folder as plugin.yml.
    picture below
    http://www.ladda-upp.se/bilder/mijkupkiemhu/
     
  5. Offline

    nopresnik

    masj2
    You have placed the 'files' in the wrong place.
    The files package downloaded is supposed to go in the same directory as your source code. So drop those files the package into your 'src' directory.
     
  6. Offline

    masj2

    What package? All I got was 3 files.
     
  7. Offline

    -_Husky_-

  8. Offline

    nopresnik

    -_Husky_- likes this.
  9. Offline

    -_Husky_-

    Glad it worked. :)
     
  10. Offline

    masj2

    basics2.png
    Is this setup correct? I still get errors. Im new to both java and github.
     
  11. Offline

    -_Husky_-

    Add
    Code:
    import code.husky.*;
    To your imports, or hover over MySQL and import using eclipse. :)
     
  12. Offline

    nopresnik

    Sorry, I know this isn't an issue with your library, but what am I doing wrong?
    I created a method to check how many notes a player has (count how many times the username appears in the DB)
    Here is the method;
    Code:java
    1. public ResultSet getNoteCount(String username) {
    2. try {
    3. Statement s = plugin.c.createStatement();
    4. ResultSet res = s.executeQuery("SELECT COUNT(*) FROM `NopBans`.`notes` WHERE username = '" + username.toString() + "';");
    5. if (res.next()) {
    6. return res;
    7. }
    8. } catch (SQLException ex) {
    9. Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex);
    10. }
    11. return null;
    12. }

    And here is the command to execute the method;

    Code:java
    1. if (command.getName().equalsIgnoreCase("getnotecount")) {
    2. String username = args[0];
    3. ResultSet count = plugin.api.getNoteCount(username);
    4. sender.sendMessage(count.toString());
    5. return true;
    6. }


    When the command is executed, it returns something like this in the chat com.mysql.jdbc.JDBC4ResultSet@88d7fd1the "88d7fd1" changes each time the command is run.
     
  13. Offline

    masj2

    I dont get any red lines anymore but when i run it says:
    Could not lod 'plugins\basics.jar' in folder 'plugins'
    org.bukkit.plugin.InvalidPluginException: Java.lang.NoClassDefFoundError: code/husky/MySQL
    at org.bukkit.plugin.java.JavaPluginManager.loadPlugin<JavaPluginLoader.java:182>
    etc...
     
  14. Offline

    -_Husky_-

    nopresnik

    Code:
    ResultSet count = plugin.api.getNoteCount(username);
    Problem here is getNoteCount() returns a ResultSet, not the actual number.

    Code:
    public ResultSet getNoteCount(String username) {
    Show me your plugin.yml?

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

    masj2

    -_Husky_-
    Code:
    name: Basics
    main: me.masj2.Basics
    version: 1.0
    description: >
                Basic features.
    commands:
      sethome:
        description: sethome
      home:
        description: home
     
  16. Offline

    -_Husky_-

    And the project setup?
     
  17. Offline

    masj2

    -_Husky_-
    What do you mean? I posted a screenshot above.
     
  18. Offline

    -_Husky_-

    masj2

    Ah, remove mysql-connector

    Hope it helps, Husky.
     
  19. Offline

    nopresnik

    -_Husky_-
    I see, silly mistake I made :p All working now.
    Thanks
     
    -_Husky_- likes this.
  20. Offline

    masj2

    -_Husky_-
    I did remove the connector but when i run MySQL.openConnection() in onEnable() it crash. Do i have to send in Connector c to the funktion with arguments?
     
  21. Offline

    -_Husky_-

    Can I have a stack trace?
     
  22. Offline

    masj2

  23. Offline

    nopresnik

    -_Husky_-
    Last question, I swear!

    This code here is only returning the first result in list
    username = pdavinci
    Code:java
    1. public String getNotes(String username) {
    2. try {
    3. Statement s = plugin.c.createStatement();
    4. ResultSet res = s.executeQuery("SELECT CONCAT('Note #',id,' (',issuer,') [',note,']') AS RECORD FROM `notes` WHERE username = '" + username + "';");
    5. if (res.next()) {
    6. return res.getString(1);
    7. }
    8. } catch (SQLException ex) {
    9. Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex);
    10. }
    11. return null;
    12. }


    My table looks like this.
    [​IMG]


    When I execute the command, it looks like this. It is only displaying the first result on the list
    [​IMG]

    However, when I execute the query through phpmyadmin, it lists all of the results and not just the first one on the top of the list.
    [​IMG]

    Do you know what's going on here?
     
  24. Offline

    -_Husky_-

    nopresnik

    Simple. :)
    Code:java
    1.  
    2. public String getNotes(String username) {
    3. try {
    4. Statement s = plugin.c.createStatement();
    5. ResultSet res = s.executeQuery("SELECT CONCAT('Note #',id,' (',issuer,') [',note,']') AS RECORD FROM `notes` WHERE username = '" + username + "';");
    6. while (res.next()) {
    7. return res.getString(1);
    8. }
    9. } catch (SQLException ex) {
    10. Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex);
    11. }
    12. return null;
    13. }
    14.  


    That's not going to do what you want it to, you're going to have to run this chunk of code in the command.

    Pseudo code:
    Code:java
    1. public boolean onCommand () {
    2. Player p = (Player) sender;
    3. if (cmd.getName().equalsIgnoreCase("blah") {
    4. try {
    5. Statement s = plugin.c.createStatement();
    6. ResultSet res = s.executeQuery("SELECT CONCAT('Note #',id,' (',issuer,') [',note,']') AS RECORD FROM `notes` WHERE username = '" + username + "';");
    7. while (res.next()) { // loops over ResultSet for more data, not checking once, like an 'if' statement would.
    8. p.sendMessage(res.getString(1));
    9. }
    10. } catch (SQLException ex) {
    11. Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex);
    12. }
    13. }


    Please excuse the formatting. :p
     
  25. Offline

    nopresnik

    -_Husky_-
    I see now, thank you.
    I did try the while loop in the method but it didn't work like you said. I wasn't aware it had to be in the command.
     
    -_Husky_- likes this.
  26. Offline

    -_Husky_-

    It's because you can't return more than 1 value from a method, I'm sure there's ways around it, but easiest way is to throw it in the command.

    Anyway, glad it worked. :)
     
  27. Offline

    masj2

    -_Husky_-
    Is there a basic mainfile that works avalible for download?
     
  28. Offline

    -_Husky_-

    Sorry, can you elaborate?
     
  29. Offline

    masj2

    Because my code doesnt work maybe there is a file that does work that i can get and see what i did wrong.
     
  30. Offline

    -_Husky_-

    Erm, post your code and I'll help you fix. People's use of the MySQL Library is going to differ, therefore a 'mainfile' would be useless.

    Thanks, Husky.
     
Thread Status:
Not open for further replies.

Share This Page