I'm trying to add a row in my database, at the table employee. But i get an exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ConnectionBD.EmployeeBD.add(EmployeeBD.java:56)`
This is my source code (EmployeeBD Class):
public void add() throws SQLException, ClassNotFoundException {
56 Employee a = ep.ReadEmployee();
57 if (a!=null) {
58 Connection conn = null;
try {
Class.forName(BDConnect.DRIVER);
conn = DriverManager.getConnection(BDConnect.BD_URL, BDConnect.USUARI, BDConnect.PASSWORD);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
if (conn != null) {
String sql = "SELECT * FROM employee";
ResultSet rs = stmt.executeQuery( sql );
rs.moveToInsertRow();
rs.updateString( "nif", a.getNif());
rs.updateString( "name", a.getName());
rs.updateDouble( "salary",a.getSalary());
System.out.println("Added Suscefully");
rs.insertRow();
rs.moveToCurrentRow();
} else {
System.out.println("Can't get DB");
}
} catch (SQLException ioe) {
System.out.println(ioe);
} catch(ClassNotFoundException ex) {
System.out.println(ex);
}
}
}
And the ReadEmployee() Method:
public Employee ReadEmployee() {
String nif = null;
String name = null;
Double salary = null;
int depId = 0;
nif = jTextField1.getText();
name = jTextField2.getText();
salary = Double.parseDouble(jTextField3.getText());
Employee emp = new Employee(nif, name, salary, 1);
if (name.equals("") || nif.equals("") || salary != null) {
return emp;
} else {
JOptionPane.showMessageDialog(this, "Fill all TextFields", "Article warning", JOptionPane.WARNING_MESSAGE);
return null;
}
}
Why It throws the exception? I don't know how to do it correcty!
conn != nullbefore you callcreateStatementon itif (name.equals("") || nif.equals("") || salary != null) {This isn't working as check for empty values. You want to return emp if all fields are filled, but you are returning emp if name or nif are empty and salary must be different than null. To check it correctly you must useif (!name.equals("") && !nif.equals("") && salary != null) {return emp;}and for theelsecondition, if you want to throw the message when only a single field it's not filled up useelse if (name.equals("") || nif.equals("") || salary == null) {