2014-04-23 4 views
0

레코드를 데이터베이스에 삽입하려고 할 때 널 포인터 예외가 계속 발생합니다. 나는 넷 애플 리케이션 클래스에있어, 내 일식 내에서 데이터베이스를 다루는 내 처음이다. 이 줄은 내 연결 변수를 초기화한다고 생각합니다.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(); 
    } 

} 

} 
+0

'addCustomer()'를 호출하기 전에'AddCustomerQuery()'(나쁜 이름 인 btw)를 호출합니까? – alfasin

+1

Class.forName ("com.mysql.jdbc.Driver"); 즉, newInstance()를 제거하면됩니다./ – KNU

+0

@ user3562811이 방법으로이 클래스의 객체를 사용하거나 인스턴스화해야합니다 : 'AddCustomerQuery objReference = new AddCustomerQuery ("CUSTOMER_TABLE", "root", "root");'그런 다음 objReference.addCustomer (customerObj)로 사용하십시오 – KNU

답변

0

먼저 확인하여 MySQL의 daatbase 서버 사용자 이름, 암호, 데이터베이스 이름 등. 기본적으로 mysql 서버 포트 번호는 3306이므로 설치하는 동안 서버의 포트 번호를 변경할 수 있습니다.

+0

문제를 해결했습니다. 나는 운전사를 놓치고 있었다. – user3562811

관련 문제