0

I tried to insert some data into my database table using JDBC, but it throws some exception like--> java.lang.NullPointerException There is no error in my connection I guess! enter image description here

Here is the code-->

package batch2;

public class Database {
    Connection con;
    Statement stm;
    
    Database(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/javabatch2", "root", "");
        } 
        catch (Exception ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }
    
    public void addStudent(String name, String phone, String email){
        String sql= "insert into student(name, phone,email) values ('"+name+"',  '"+phone+"',    '"+email+"')";
        
        try{
            stm.execute(sql);
        }catch(Exception ex){
             System.out.println(ex);   ***//exception trows here***
        }
        
    }

}

Here is my main class-->

package batch2;

public class Main1 {
      public static void main(String[] args){
        Database obj = new Database();
        
        obj.addStudent("hola", "875423", "hola@gmail.com");
        System.out.println("Added into student table DONE");
    }
    
}

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tuhin
  • 194
  • 4
  • 16

1 Answers1

2

In Database.addStudent() you are using stm.execute(..) but from the code you have provided you never initialize stm, so stm is null.

Note that you do System.out.println(ex) which doesn't print the stacktrace. You could instead do ex.printStackTrace() or log it with your logger (like in the constructor) so you would have the full stack trace and you would see right away where the problem is.

Also note that in your Database constructor you catch the exception, log it, and do nothing about it. This means if something happens there your con connection will be null and things will fail further down the line. It would be good practice to handle the error case rather than do nothing and let it blow up further down the line.

vmallet
  • 479
  • 3
  • 11