Database for a report plugin

Discussion in 'Plugin Development' started by Krame, Sep 1, 2015.

Thread Status:
Not open for further replies.
  1. Hello guys,
    I'm trying to make a Database for a report plugin, but after database connection , when i try to use the command "/report " it doesn't work and i get a list of errors.


    I'm using an utility pack: https://github.com/Huskehhh/MySQL

    I made two class:

    Report.java:
    Code:
    package krame.report;
    
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.logging.Level;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.mysql.jdbc.Connection;
    
    
    public class Report extends JavaPlugin{
       
        public MySQLManager mysql = new MySQLManager(this);
        public boolean logDB = true;
        private Report main;
        Connection conn = null;
       
        public void log(String s,Level l){
            getLogger().log(l, "[RP] " + s);
        }
       
        public void onEnable(){
           
            try{
                conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/pluginreport","root","root");
                this.log("Connessione al database Report effettuata!", Level.INFO);
               
            } catch (Exception e) {
                this.log("Errore inaspettato in Report", Level.INFO);
            }
           
        }
       
        public void onDisable(){
           
            try{
                conn.close();
                this.log("Report disabilitato.", Level.INFO);
            }
            catch (Exception e) {
                this.log("Impossibile disabilitare Report.", Level.INFO);;
            }
           
        }
       
       
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel,String[] args){
           
            if(cmd.getName().equalsIgnoreCase("report")){
                if(args.length == 0){
                    sender.sendMessage(ChatColor.RED + "Prova con: /report <giocatore>");
                }
               
                Player p =  (Player) sender;
                p= p.getPlayer();
               
                if(this.main.logDB){
                   
                    try {
                        this.main.mysql.updatePlayer(p);
                       
                    }
                    catch (ClassNotFoundException | SQLException e) {
                        this.main.log("Non posso aggiornare il giocatore "
                                + p.getPlayer().getDisplayName(), Level.WARNING);
                        this.main.log("Error: ", Level.WARNING);
                    }
                   
                }
            }
           
            return true;
        }
    
       
    }
    

    MySQLManager.java
    Code:
    package krame.report;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.bukkit.entity.Player;
    
    import code.husky.mysql.MySQL;
    
    public class MySQLManager {
       
        @SuppressWarnings("unused")
        private final Report main;
        private MySQL db;
       
        public MySQLManager(Report h){
            this.main = h;
        }   
       
        public int getUses (Player p) throws ClassNotFoundException, SQLException{
            String pname = p.getDisplayName().toLowerCase();
            if(!this.db.checkConnection())
                this.db.openConnection();
           
            Statement statement = this.db.getConnection().createStatement();
            ResultSet rs = statement.executeQuery("SELECT * FROM `report` WHERE `giocatore` =`"+pname+"`;");
           
            if(!rs.next())
                return 0;
           
           
            return rs.getInt("nreport");
        }
       
        public void updatePlayer(Player p) throws ClassNotFoundException, SQLException{
            String pname = p.getDisplayName().toLowerCase();
            if(!this.db.checkConnection())
                this.db.openConnection();
           
            Statement statement = this.db.getConnection().createStatement();
            int uses = this.getUses(p);
           
            if(uses != 0){
                //Aggiornamento
                statement.executeUpdate("UPDATE `report` SET `nreport` =`"+(uses+1)+"` WHERE `giocatore` =`"+pname+"`;");
                statement.close();
            }
            else{
                //Inserisci
                statement.executeUpdate("INSERT * `report` (`giocatore`,`nreport`) VALUE (`" + pname +"`, `1`);");
                statement.close();
            }
           
        }
       
    }

    Sorry for my bad english :/ and thanks :)
     
  2. Offline

    mythbusterma

    @Krame

    Actually showing us the error would be helpful.

    Also, don't run SQL queries on the main thread, unless you're a huge fan of lag.

    Furthermore, use prepared statements, and get rid of that "Husky" crap.
     
    Oxyorum and mine-care like this.
  3. @mythbusterma
    It is the error, when i try to type "/report" it don't work!
    Thank you for the help! :)
    [​IMG]
     
  4. Offline

    Oxyorum

    @Krame Make sure to check that the sender is actually a Player before casting.
     
  5. @Oxyorum
    I fix it , i put Player p = (Player) sender before the "if(cmd.getName().equalsIgnoreCase("report"))" ,but it still doesn't work :/
     
  6. Offline

    Oxyorum

    @Krame, If that's all you did, you did not fix it. xD

    You still are not checking to see if the sender is actually a Player or the console.
     
  7. @Oxyorum
    I add a new if statement:

    if (!(sender instanceof Player)) {
    sender.sendMessage(ChatColor.RED + "You must be a player!");
    }

    Now only player can use "/report"

    But if i use "/report" in the console, i get errors:

    [​IMG]

    :/ i don't know why this error, i really need help . Thanks.
     
  8. Offline

    RoboticPlayer

    When you got this error, did the console send it or a player?
     
  9. Offline

    Oxyorum

    @Krane Your code is still throwing a ClassCastException, so whatever you are doing now did not resolve the problem.

    You need to have it so the part of your code that casts sender to Player class only runs if the sender is actually a player, like below:

    Code:java
    1.  
    2. if (!(sender instanceof Player)) {
    3. sender.sendMessage(ChatColor.RED + "You must be a player!");
    4. return true;
    5. }
    6. else{
    7. //Cast sender to player and other things you want to do.
    8. }
    9.  
     
  10. @Oxyorum
    Ok, i add it in the code and the other things are comment, now i don't get error if i use "/report"

    But if i leave the comment and i try to use sql stament, i get the errors :/
    Code:
    package krame.report;
    import java.sql.DriverManager;
    //import java.sql.SQLException;
    import java.util.logging.Level;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    import com.mysql.jdbc.Connection;
    public class Report extends JavaPlugin{
    
        public MySQLManager mysql = new MySQLManager(this);
        public boolean logDB = true;
    //    private Report main;
        Connection conn = null;
    
        public void log(String s,Level l){
            getLogger().log(l, "[RP] " + s);
        }
    
        public void onEnable(){
        
            try{
                conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/pluginreport","root","root");
                this.log("Connessione al database Report effettuata!", Level.INFO);
            
            } catch (Exception e) {
                this.log("Errore inaspettato in Report", Level.INFO);
            }
        
        }
    
        public void onDisable(){
        
            try{
                conn.close();
                this.log("Report disabilitato.", Level.INFO);
            }
            catch (Exception e) {
                this.log("Impossibile disabilitare Report.", Level.INFO);;
            }
        
        }
    
    
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel,String[] args){
        
    //        Player p =  (Player) sender;
         
            if(cmd.getName().equalsIgnoreCase("report")){
            
                if(args.length == 0){
                    sender.sendMessage(ChatColor.RED + "Prova con: /report <giocatore>");
                    return true;
                }
             
                if (!(sender instanceof Player)) {
                    sender.sendMessage(ChatColor.RED + "You must be a player!");
                    return true;
                    }
                    else{
                        sender.sendMessage("L'utente " + args[0] + " è stato reportato con successo!");
                    }
             
             
            
    //            p= p.getPlayer();
    //        
    //            if(this.main.logDB){
    //            
    //                try {
    //                    this.main.mysql.updatePlayer(p);
    //                
    //                }
    //                catch (ClassNotFoundException | SQLException e) {
    //                    this.main.log("Non posso aggiornare il giocatore "
    //                            + p.getPlayer().getDisplayName(), Level.WARNING);
    //                    this.main.log("Error: ", Level.WARNING);
    //                }
                
    //            }
                return true;
            }
        
            return true;
        }
    
    }
     
    Last edited: Sep 2, 2015
  11. Offline

    mythbusterma

    @Krame

    You're going to have to show us the errors if you want help.
     
  12. Last edited by a moderator: Sep 3, 2015
  13. Offline

    mythbusterma

    @Krame

    You're doing something that's causing the server to time out.
     
  14. @mythbusterma
    Ye, can you give me one example of mysql database for bukkit plugin?
     
  15. Offline

    mythbusterma

  16. Offline

    stormneo7

    Code:
    Player p = (Player) sender;
    p= p.getPlayer();
    You're declaring a player without a check.
    In addition, you're executing the command through Console when you're specifically declared the sender as a Player.
     
    mine-care likes this.
  17. @stormneo7 Ye i know this, but if i use command in game with a Player i get the same error :/

    @mythbusterma
    Thank you ^^

    @mythbusterma @stormneo7
    I try to fix all, now i can't connect in the database :/

    Code:
    package krame.report;
    
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import com.mysql.jdbc.Connection;
    
    public class Reporter extends JavaPlugin {
      
        private FileConfiguration config;
        private boolean connection = false;
        private boolean debug;
        private Connection conn;
      
      
        public void onEnable(){
          
            config = getConfig();
            config.options().copyDefaults(true);
            saveConfig();
          
          
            try {
                   Class.forName("com.mysql.jdbc.Driver");
                conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/pluginreport","root","root");
                connection = true;
            }catch(Exception ex) {
                System.out.println(config.getString("msg.sql-error"));
                if(debug) {ex.printStackTrace();}
            }
          
            if (connection) {
                setupDB();
              
         }
        }
      
      
      
      
        public void onDisable() {
            try {
                conn.close();
            }catch(Exception ex) {
                if(debug) {ex.printStackTrace();}
            }
        }
      
      
      
      
      
      
        public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) {
          
    
                    try {
                        if(cmd.getName().equalsIgnoreCase("report")){
                          
                            if(args.length == 0){
                                sender.sendMessage(ChatColor.RED + "Prova con: /report <giocatore> !");
                            }
                          
                          
                            if(sender instanceof Player){
                                String giocatore = args[0];
                                dbUpdate(giocatore);
                                sender.sendMessage(ChatColor.GREEN + "Il giocatore " + giocatore + " è stato reportato,"+
                                                   "un moderatore analizzerà la situazione!");
                            }
                            else{
                                sender.sendMessage("Devi essere un giocatore per utilizzare questo comando!");
                            }
                            return true;
                        }  
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
              
              
              
    
            return true;
        }
      
      
        public int getUses (String giocatore) throws SQLException{
            String pname = giocatore;
                  
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM `report` WHERE `GIOCATORE` =`"+pname+"`;");
         
            if(!rs.next())
                return 0;
         
         
            return rs.getInt("NREPORT");
        }
      
      
      
        private void dbUpdate(String giocatore) throws SQLException{
          
             String pname = giocatore;
             int uses = this.getUses(giocatore);
              
            try{
                Statement stmt = conn.createStatement();
              
                if(uses != 0){
                    //Aggiornamento
                    stmt.executeUpdate("UPDATE `report` SET `NREPORT` =`"+(uses+1)+"` WHERE `GIOCATORE` =`"+pname+"`;");
                    stmt.close();
                }
                else{
                    //Inserisci
                    stmt.executeUpdate("INSERT * `report` (`GIOCATORE`,`NREPORT`) VALUE (`" + pname +"`, `1`);");
                    stmt.close();
                }
              
            }
            catch(Exception ex) {
                System.out.println(config.getString("msg.sql-error"));
            }
          
          
        }
      
      
      
      
      
      
      
      
        private boolean setupDB() {
            try {
                Statement stmt = conn.createStatement();
                String query = "CREATE TABLE IF NOT EXISTS report" +
                           "(ID       int(11) PRIMARY KEY  NOT NULL AUTO_INCREMENT, " +
                           "(UUID         CHAR(40)  NOT NULL, " +
                           "GIOCATORE         CHAR(40)  NOT NULL, " +
                           "NREPORT         int(11) , " +
                           ");";
                stmt.executeUpdate(query);
                stmt.close();
              
                stmt = conn.createStatement();
                query = "CREATE TABLE IF NOT EXISTS backup" +
                           "(ID       int(11) PRIMARY KEY  NOT NULL AUTO_INCREMENT, " +
                           "(UUID         CHAR(40)  NOT NULL, " +
                           "GIOCATORE         CHAR(40)  NOT NULL, " +
                           "NREPORT         int(11) , " +
                           ");";
                stmt.executeUpdate(query);
                stmt.close();
                return true;
            }catch(Exception ex) {
                System.out.println(config.getString("msg.sql-error"));
                if(debug) {ex.printStackTrace();}
            }
            return false;
        }
      
      
    }
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 11, 2016
Thread Status:
Not open for further replies.

Share This Page