0
votes

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();
    }

}

}
1
Do you call AddCustomerQuery() (bad name btw) before calling addCustomer() ?Nir Alfasi
try Class.forName("com.mysql.jdbc.Driver"); i.e. remove newInstance() it worked for me that way :/KNU
@user3562811 you must use/instantiate the object of this class this way : AddCustomerQuery objReference = new AddCustomerQuery("CUSTOMER_TABLE", "root","root"); and then use it as objReference.addCustomer(customerObj)KNU

1 Answers

0
votes

First check your mysql daatbase server username,password,database name etc..,. Because by default mysql server port number is 3306,may be while installation time you changed port number of your server.