MySQL Connection

Discussion in 'Spigot Plugin Development' started by Ehrenmann, Jul 7, 2018.

  1. !! This is not related with Spigot just a Java Question!

    I got this error:
    Code (Text):
    java.lang.NullPointerException
        at MainFrame.ConnectMySQL(MainFrame.java:50)
        at MainFrame.<init>(MainFrame.java:46)
        at MainFrame$1.run(MainFrame.java:32)
        at java.awt.event.InvocationEvent.dispatch(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$500(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)
    Here is the connection code causing the error:
    Code (Java):
    public Connection connect() {
            if (connection == null) {
                try {
                    Class.forName(DATABASE_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                } catch (ClassNotFoundException | SQLException e) {
                    e.printStackTrace();
                }
            }
            return connection;
        }
    Rest of the MySQL Connection class:
    Code (Java):
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;

    public class MySQLConnection {
        private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
        private static final String DATABASE_URL = "jdbc:mysql://host:3306/kstats"; // I removed host so you dont see it
        private static final String USERNAME = ""; // I removed password and everything so you dont see it
        private static final String PASSWORD = "";
        private static final String MAX_POOL = "250";

        private Connection connection;
        private Properties properties;

        private Properties getProperties() {
            if (properties == null) {
                properties = new Properties();
                properties.setProperty("user", USERNAME);
                properties.setProperty("password", PASSWORD);
                properties.setProperty("MaxPooledStatements", MAX_POOL);
            }
            return properties;
        }

        public Connection connect() {
            if (connection == null) {
                try {
                    Class.forName(DATABASE_DRIVER);
                    connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                } catch (ClassNotFoundException | SQLException e) {
                    e.printStackTrace();
                }
            }
            return connection;
        }
       
        public ResultSet query(String qry) {
            ResultSet rs = null;

            try {
                Statement st = (Statement) connection.createStatement();
                rs = st.executeQuery(qry);
            } catch (SQLException e) {
                connect();
                System.err.println(e);
            }
            return rs;
        }
       
        public void update(String qry) {
            try {
                Statement st = (Statement) connection.createStatement();
                st.executeUpdate(qry);
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public void disconnect() {
            if (connection != null) {
                try {
                    connection.close();
                    connection = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    Please Help me :D
     
    • Creative Creative x 1
  2. An NPE is when you invoke a method/field on a null reference. Show us line 50 in MainFrame class
     
  3. This is line 50
    Code (Java):
    mysql.connect();
    (public static MySQLConnection mysql;)
     
  4. mysql is null then. ^_^
     
  5. Yeah, this is what the error says, would be great if you could help me out there im clueless xd
     
  6. Hard to say since you didnt post any relevant code to the issue.
     
  7. i posted everytthing related to mysql.connect

    But if you also want the MainFrame Class:

    Code (Java):
    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import java.awt.BorderLayout;
    import javax.swing.SwingConstants;

    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JLabel;
    import java.awt.Font;
    import java.awt.Window;
    import java.awt.Color;
    import javax.swing.JPasswordField;

    public class MainFrame {

        private JFrame frmCookieclickerByEnderoffice;
        private JTextField userNameField;
        private JLabel log = new JLabel("");
        public static MySQLConnection mysql;
        public static MainFrame main;
        private JPasswordField passwordField;

        /**
         * Launch the application.
         */

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MainFrame window = new MainFrame();
                        window.frmCookieclickerByEnderoffice.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */

        public MainFrame() {
            initialize();
            ConnectMySQL();
        }

        private void ConnectMySQL() {
            mysql.connect();
            mysql.update("CREATE TABLE IF NOT EXISTS CClicker(NAME varchar(64), PASSWORD varchar(64));");
        }

        /**
         * Initialize the contents of the frame.
         */

        private void initialize() {
            frmCookieclickerByEnderoffice = new JFrame();
            frmCookieclickerByEnderoffice.setResizable(false);
            frmCookieclickerByEnderoffice.setTitle("CookieClicker by EnderOffice");
            frmCookieclickerByEnderoffice.setBounds(100, 100, 388, 275);
            frmCookieclickerByEnderoffice.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frmCookieclickerByEnderoffice.getContentPane().setLayout(null);
           
            //Login vorgang
           
            JButton btnLogin = new JButton("Login");
            btnLogin.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    if(userNameField.getText().equals("EnderOffice") && passwordField.getText().equals("uhbvfr4321")) {
                        log.setForeground(Color.GREEN);
                        log.setText("Erfolgreich Eingeloggt!");
                    } else {
                        log.setForeground(Color.RED);
                        log.setText("Die Daten sind nicht richtig!");
                    }
                }
            });
           
           
            btnLogin.setBounds(71, 178, 113, 33);
            frmCookieclickerByEnderoffice.getContentPane().add(btnLogin);
           
            //Registrieren
           
            JButton btnRegistrieren = new JButton("Registrieren");
            btnRegistrieren.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                   
                }
            });
           
            btnRegistrieren.setBounds(194, 178, 113, 33);
            frmCookieclickerByEnderoffice.getContentPane().add(btnRegistrieren);
           
            userNameField = new JTextField();
            userNameField.setBounds(71, 104, 236, 20);
            frmCookieclickerByEnderoffice.getContentPane().add(userNameField);
            userNameField.setColumns(10);
           
            JLabel lblNewLabel = new JLabel("Name");
            lblNewLabel.setBounds(35, 107, 63, 14);
            frmCookieclickerByEnderoffice.getContentPane().add(lblNewLabel);
           
            JLabel lblNewLabel_1 = new JLabel("Password");
            lblNewLabel_1.setBounds(10, 138, 72, 14);
            frmCookieclickerByEnderoffice.getContentPane().add(lblNewLabel_1);
           
            JLabel lblCookieclicker = new JLabel("CookieClicker");
            lblCookieclicker.setFont(new Font("Thruster", Font.BOLD, 33));
            lblCookieclicker.setHorizontalAlignment(SwingConstants.CENTER);
            lblCookieclicker.setBounds(10, 30, 352, 41);
            frmCookieclickerByEnderoffice.getContentPane().add(lblCookieclicker);
           
            log.setHorizontalAlignment(SwingConstants.CENTER);
            log.setBounds(71, 79, 236, 14);
            frmCookieclickerByEnderoffice.getContentPane().add(log);
           
            passwordField = new JPasswordField();
            passwordField.setBounds(71, 135, 236, 20);
            frmCookieclickerByEnderoffice.getContentPane().add(passwordField);
        }
    }
     
  8. I dont see anywhere in there where you instantiated mysql. It's declared but never set, so it's always null.
     
    • Like Like x 1
  9. so i have to do what? Sorry i know what you mean but i dont know what to do in this situation
     
  10. Basically, you made a variable called mysql, but never gave it a value. You then tried to use the variable but it’s STILL null.
     
    • Like Like x 1
    • Agree Agree x 1
  11. For clarity, this occurs when you try to call something on a variable - not when it is used ;)
    You can pass null variables into a lot of methods.

    Give the variable a value. Probably a new instance of your MySQLConnection class.

    Also, your code breaks several coding conventions. You shouldn't capitalize method names, and probably should move the hardcoded values in MySQLConnection to a configuration file. And you should put your classes in a package.
     
    • Like Like x 1
    • Agree Agree x 1
  12. Thanks for your advice! i didnt use a package yet because its just a little test and i dont want to finish it