레코드를 데이터베이스에 삽입하려고 할 때 널 포인터 예외가 계속 발생합니다. 나는 넷 애플 리케이션 클래스에있어, 내 일식 내에서 데이터베이스를 다루는 내 처음이다. 이 줄은 내 연결 변수를 초기화한다고 생각합니다.PreparedStatement는 java.lang.NullPointerException을 던졌습니다
this.connection = DriverManager.getConnection(url, uname, pwd);
...하지만 여전히 연결은 null이라고 말합니다. 그것은을 의미 라인은 다음과 같습니다
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();
}
}
}
'addCustomer()'를 호출하기 전에'AddCustomerQuery()'(나쁜 이름 인 btw)를 호출합니까? – alfasin
Class.forName ("com.mysql.jdbc.Driver"); 즉, newInstance()를 제거하면됩니다./ – KNU
@ user3562811이 방법으로이 클래스의 객체를 사용하거나 인스턴스화해야합니다 : 'AddCustomerQuery objReference = new AddCustomerQuery ("CUSTOMER_TABLE", "root", "root");'그런 다음 objReference.addCustomer (customerObj)로 사용하십시오 – KNU