2013-11-26 2 views
0

현재 학교에서 심도있게 다루고 있으며 sql을 사용하여 간단한 로그인 양식을 프로그래밍 할 것을 기대하고 있습니다. JDBC를 사용하는 방법과 모든 것을 간단한 예제를 통해 제공했지만, 실제로 사용하는 방법을 단계별로 설명하지는 않았습니다. 따라서 예제에서 약간의 코드를 가져 왔지만 제대로 작동하지 않습니다.MySQL과 간단한 데이터 비교, nullpointerexception

package Database; 

import java.sql.*; 

public class MySQLConnection { 

    public static final String DRIVER = "com.mysql.jdbc.Driver"; 
    public static final String DBURL = "jdbc:mysql://localhost/corendon"; 
    public static final String DBUSER = "root"; 
    public static final String DBPASS = "simplepass"; 
    private ResultSet result = null; 
    private int affectedRows = -1; 
    Connection conn = null; 

    public void startConnection() { 
     try { 

      Class.forName(DRIVER); 
      DriverManager.setLoginTimeout(5); 
      conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); 

     } catch (Exception e) { 
     } 
    } 

    public void closeConnection() { 
     try { 
      if (conn != null && !conn.isClosed()) { 
       conn.close(); 
      } 
     } catch (Exception e) { 
     } 
     conn = null; 
    } 

    public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException { 
     result = prdstmt.executeQuery(); 

     return result; 
    } 

    public int performUpdate(PreparedStatement prdstmt) throws SQLException { 

     affectedRows = prdstmt.executeUpdate(); 

     return affectedRows; 
    } 

    public Connection getConnection() { 
     return conn; 
    } 
} 

그리고 여기에 내가 (다른 클래스)에서 예외를 받고 있어요하는 방법입니다 : :(

가 여기에 연결 클래스의 이유는, NullPointerException가 수신 계속하고 난 알아낼 수 없습니다 :

prdstmt = conn.getConnection().prepareStatement(query); 

왜 내가 작업을 수행합니다

MySQLConnection conn = new MySQLConnection(); 

public void compareData(int id, String pass) throws SQLException{ 
    ResultSet rs = null; 
    PreparedStatement prdstmt = null; 

    String query = "SELECT id, password FROM users WHERE id=?, password=?"; 

    conn.startConnection(); 

    prdstmt = conn.getConnection().prepareStatement(query); 
    prdstmt.setInt(1, id); 
    prdstmt.setString(2, pass); 

    rs = conn.performSelect(prdstmt); 

    while (rs.next()){ 
     String tempPass = rs.getString("password"); 
     int tempId = rs.getInt("id"); 
    } 

    if(conn != null){ 
     conn.closeConnection(); 
    } 
} 

나는 라인에 NullPointerException이 받고 있어요 거기에 예외를 던지지 만, 내가 연결을 시작할 때가 아니라 어떻게 이것을 해결할 수 있을까요? 미리 감사드립니다. 당신이 startConnection()를 호출 할 때

+0

compareData 메소드에서 변수 'conn'는 어떤 종류의 객체입니까? 'DataSource' 나'Connection' 객체 중 어느 것도 그것도 가지고 있지 않지만 startConnection() 메소드를 선언합니다 – hotforfeature

+0

SQL Server 또는 MySQL을 사용하고 있습니까? 질문 제목은 SQL Server를 말하지만 질문의 나머지 부분은 MySQL을 말합니다. –

+0

conn는 내가 처음 게시 한 클래스의 객체입니다. 클래스의 앞부분에서 MySQLConnection conn = new MySQLConnection(); 그리고 네, 죄송합니다. 죄송합니다. – Taerus

답변

0

, 당신은()의 getConnection를 호출 할 때 NullPointerException을 던지고있는의 conn 변수가 여전히 null이며, 따라서 Exception

public void startConnection() { 
     try { 

      Class.forName(DRIVER); 
      DriverManager.setLoginTimeout(5); 
      conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); 

     } catch (Exception e) { 
      //An exception occurs here, but you don't do anything about it 
     } 
    } 

을 던지고있다.

어느 startConnection()는 당신이 그것을 다룰 수밖에 있도록 (이것은 일반적으로 대부분의 JDBC 드라이버가 어쨌든 작동하는 방법입니다) 예외를 던져, 또는 당신이 그것을 사용하기 전에 conn 변수가 null을 있는지 확인합니다.

public void compareData(int id, String pass) throws SQLException{ 
    ResultSet rs = null; 
    PreparedStatement prdstmt = null; 

    String query = "SELECT id, password FROM users WHERE id=?, password=?"; 

    conn.startConnection(); 

    if (conn.getConnection() == null) { 
     throw new SQLException("Connection is null!"); 
    } 

또는 (나는 개인적으로 더 좋을 것이다 생각)

public void startConnection() throws Exception { 
      Class.forName(DRIVER); 
      DriverManager.setLoginTimeout(5); 
      conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); 
    } 

public void compareData(int id, String pass) throws SQLException{ 
     ResultSet rs = null; 
     PreparedStatement prdstmt = null; 

     String query = "SELECT id, password FROM users WHERE id=?, password=?"; 

     try { 
      conn.startConnection(); 
     } catch (Exception e) { 
      throw new SQLException(e); 
     } 

는 또한 팁으로, 당신은 아마 당신이 사용하는 다른 클래스와 동일한 이름으로 클래스를 선언 피해야한다. 이 모든 것은 자신의 MySQLConnection 클래스에서 발생하지만 실제로는 com.mysql.jdbc.MySQLConnection 클래스와 혼동을 줄 수 있습니다.

+0

고마워요, 당신 말이 맞습니다. 캐치에 printStackTrace를 추가하고 실제로 ClassNotFoundException을 보여줍니다. 나는 뭔가 잘못 가져 왔을지도 모른다. 또한 항상 공백으로 두지 않고 예외를 처리하는 방법을 배웠습니다. 감사합니다. – Taerus

+0

그런 경우, MySQL JDBC 라이브러리가 올바른 클래스 경로에 있지 않은 것으로 들립니다. 다행 이네. 너를 도울 수있어. – hotforfeature

관련 문제