Mysql insert data not working

Discussion in 'Plugin Development' started by krifix, Oct 12, 2019.

  1. Offline

    krifix

    Hi!
    I have a problem with MYSQL inserting data.
    When I try to insert data no error appears but MYSQL is clear.
    Can you help me?


    Code:
            new BukkitRunnable () {
                public void run () {
                    try {
                        Statement stnt = Loader.getConnection().createStatement();
                        stnt.executeUpdate("INSERT INTO players (`NAM`,`RANK`) VALUES ('"+ player.getName() +"','" + "Gracz" + "');");
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }.runTaskAsynchronously(Loader.getInst());
    
    Code:
        public static void mysqlSetup() {
           
            Bukkit.getScheduler().runTaskAsynchronously(getInst(), () -> {
    
                //connect to database host
                try {
                    Class.forName("com.mysql.jdbc.Driver");
    
                    connection = DriverManager.getConnection("jdbc:mysql://mysql.titanaxe.com/xxxx", "xxxx", "xxxx");
    
                } catch (SQLException e) {
                  System.out.println(e.getMessage());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
    
            });
            Bukkit.getServer().getConsoleSender().sendMessage("§e------ MYSQL ---------");
            Bukkit.getServer().getConsoleSender().sendMessage("§fSTATUS: §aCONNECTED");
    
        }
    
    
     
  2. Offline

    timtower Moderator Moderator

  3. Offline

    krifix

  4. Offline

    timtower Moderator Moderator

    @krifix You might want to use prepared statements to start with.
    Add debug lines to your code.
    A good one is the result of executeUpdate
     
  5. Offline

    krifix

    Thank you!
    I think it was a database error.
    Now all works :)
    My code:
    Code:
            new BukkitRunnable () {
                public void run () {
                    try {
                        PreparedStatement insert = Loader.getConnection().prepareStatement("INSERT INTO players (`NAM`,`RANK`) VALUES ('"+ player.getName() +"','" + "Gracz" + "');");
                        int results = insert.executeUpdate();
                     
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }.runTaskAsynchronously(Loader.getInst());
    
    
     
  6. Offline

    Strahan

    *facepalm*

    That's not how you use prepared statements. Please read the docs. You are still vulnerable to SQL injection and formatting issues.
     

Share This Page