0

My code is supposed to search a record within the database which contains id typed into IDname JTextField. Suddenly I've got this error:

java.lang.NullPointerException
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
    at com.implementer.escuel.Implementing$1.actionPerformed(Implementing.java:55)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)

What should I do? String id is defined so why get(id) shows NPE? Are the two errors connected? I also do not quite understand why I've got that ClassNotFoundException also. Here is the code:

    JTextField IDname;
    JButton submit;


    public static Connection getConnection() throws Exception{
        try{
        String driver = "com.mysql.jdbc.Driver";
        String url = "someurl";
        String username = "";some name
        String password = "some password";
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url,username,password);
        System.out.println("Connected");
        return conn;
        } catch(Exception e){System.out.println(e);}


        return null;
        }


public Implementing() {

        IDname = new JTextField("");
        submit = new JButton("go");
        add(IDname);
        add(submit);
        submit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
        if(e.getSource() == submit) {
        try {
         String id = IDname.getText().toString();
        getConnection();
        ////////NEXT LINE IS THE NPE////////
        for(String string:get(id)){
            System.out.println(string);
        }
//       get(id);
        } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }

        }
        }


        });
        setLayout(new GridLayout());
        }

public  ArrayList<String> get(String idname) throws Exception{
        try{
        Connection con = getConnection();
        // You should replace "YourTableName" With table in databace that you work with it
        PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE ppname = '" +idname+"'");
        //If type of your id in database is Int write this code :
        //    int id= Integer.parseInt(idName); 
        //PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = " + idName);

        ResultSet result = statement.executeQuery();
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 1
    I think the `ClassNotFoundException` depends on not having `com.mysql.jdbc.Driver` in your classpath – Federico klez Culloca Aug 24 '18 at 07:56
  • You return null if you get a CNFE. Thats why you get an NPE in later code. Do not catch the base class Exception. – Jens Aug 24 '18 at 07:56
  • Frederico is right, you missed to add the right jar, please read [this](http://www.vogella.com/tutorials/MySQLJava/article.html) article how to connect to MySQL from java. Because of the ClassNotFoundException, your code could not connect to the database, and the get(id) was not able too. Therefore in your for loop the implicit iterator() function call has been called on a null value, and this results the NPE. After you fix the classpath, it will work. – m4gic Aug 24 '18 at 08:01
  • And please, do not connect every time within a loop. Your first getConnection() call should return a connection and that should be used within your loop. At the end, you should free the resources, so please close the preparedstatement, the resultset and the connection properly. If you have enough experience, you should use [SwingWorker](http://www.javapractices.com/topic/TopicAction.do?Id=153)s to keep you UI responsive during running this kind of operations. – m4gic Aug 24 '18 at 08:08
  • Use `e.printStackTrace()` in catch blocks. Printing out the name of the exception like you're doing now doesn't give you any information. – Kayaman Aug 24 '18 at 08:33

1 Answers1

1

For an explanation of the general issue problem of NPE's, please refer to:

However, there is a lot more to be said about this example.

Getting ClassNotFoundException and NullPointerException at the same time.

In fact, you are getting them one after another.

And the reason this is happening is that you are messing up the recovery aspect of exception handling. For example:

    try {
        // attempt to connect
        return conn;
    } catch(Exception e){
        System.out.println(e);
    }
    return null;

There are a number of issues with this ... but the reason this is causing you problems here is that you are returning null as the Connection. The caller doesn't expect this ... and then attempts to use the null connection and gets another exception.

In fact, what the method should do is to allow the exception to propagate so that it can be caught further up the stack ...

The second issue is that you are catching java.lang.Exception. That is almost always always a bad idea. The problem is that Exception will match (almost) all exceptions. Why is that a problem? Because there is no sensible recovery strategy if you don't know what the exception you just caught means. (Just about the only thing you can safely do in a handler for Exception is cause the application to shut down!)

The third issue is that you have declared one of your methods as throws Exception. This means that a caller of that method has to either catch Exception (bad) or propagate Exception (bad).


Now the most likely explanation of the original error is the JAR file containing the JDBC drivers for MySQL are not on the runtime classpath. That's normally a simple problem to diagnose and fix. But your mistakes in exception handling have made it complicated.


So the main lessons are:

  1. Don't catch Exception
  2. Don't declare a method as throws Exception
  3. Don't use return null to mean that something has gone wrong. Let the exception propagate instead.
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216