I keep getting a null pointer exception when trying to insert a record into a database. I'm in an into net apps class, so my this is my first time dealing with databases within eclipse. I believe this line initializes my connection variable:
this.connection = DriverManager.getConnection(url, uname, pwd);
...but it still says that connection is null. The line it refers to is:
PreparedStatement ps = connection.prepareStatement(query);
package dbHelpers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import package1.Customer;
public class AddCustomerQuery {
public Connection connection;
public AddCustomerQuery(String dbName, String uname, String pwd){
String url = "jdbc:mysql://localhost:3306/" + dbName;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.connection = DriverManager.getConnection(url, uname, pwd);
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addCustomer(Customer customer){
String query = "insert into customer (firstName, lastName, emailAddress, password, gender, phoneNumber, street, city, state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, customer.getFirstName());
ps.setString(2, customer.getLastName());
ps.setString(3, customer.getEmailAddress());
ps.setString(4, customer.getPassword());
ps.setString(5, customer.getGender());
ps.setString(6, customer.getPhoneNumber());
ps.setString(7, customer.getStreet());
ps.setString(8, customer.getCity());
ps.setString(9, customer.getState());
ps.setString(10, customer.getZip());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
AddCustomerQuery()
(bad name btw) before callingaddCustomer()
? – Nir AlfasiClass.forName("com.mysql.jdbc.Driver");
i.e. removenewInstance()
it worked for me that way :/ – KNUAddCustomerQuery objReference = new AddCustomerQuery("CUSTOMER_TABLE", "root","root");
and then use it asobjReference.addCustomer(customerObj)
– KNU