0

I have a error in inserting data into myaql table from java.error says "java.lang.NullPointerException" with prepareStatement.below is my code.please help optimize me.

package studentCon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import connection.connectionDB;

public class studentInsert {
    public static void addproduct(String Last_name,String first_name,String email,String department,int salary) {
        System.out.println(salary);
        try{  
              
            Connection con=connectionDB.getConnection();  
              
            PreparedStatement stmt=con.prepareStatement("INSERT INTO `student`.`employees` (`last_name`, `first_name`, `email`, `department`, `salary`) VALUES (?, ?, ?,?,?)");  
            stmt.setString(1,Last_name);//1 specifies the first parameter in the query  
            stmt.setString(2,first_name);
            stmt.setString(3, email);
            stmt.setString(4, department);
            stmt.setInt(5,salary);
              
            int i=stmt.executeUpdate();  
            System.out.println(i+" records inserted");  
              
            con.close();              
            }catch(Exception e){ System.out.println(e);}  
              
             
    }
    public static void main(String[] args){
        // TODO Auto-generated method stub
        
    
        addproduct("Htet","Mg","mghtet@gmail.com","IT",20000 );
    
        
    }
}

1 Answers1

0

In your exception handling code, you are printing the string representation of the error to stdout, which is why you are only seeing the NPE (NullPointerException).

At the very least, exception handling should always include some handler, or in your case, a way to view the stack trace.

You can use the method printStacktrace() for this, which would show you where your problem is

} catch(Exception e) { 
    System.out.println(e); // only prints NullPointerException
    // view the stacktrace
    e.printStacktrace();
}  
epoch
  • 16,396
  • 4
  • 43
  • 71
  • thanks for your help.i have applied it before and give me the error with prepared statement and i cannot solve it.Error code at studentCon.studentInsert.addproduct(studentInsert.java:17) at studentCon.studentInsert.main(studentInsert.java:39) java.lang.NullPointerException – Aung Kaung Htet Sep 11 '20 at 07:43
  • Keep in mind, we do not know where line 17 is in your program. When you post for help, try and make it as easy for others to help you. as others have commented, most likely your connection object is null. check the implementation there and use some print lines to try and figure out your problem ;-) – epoch Sep 11 '20 at 13:14