2014-04-21 3 views
-4

나는 나와 함께 맨 처음이다. 하지만 여기서 어딘가에 NullPointerException이 나옵니다. 어떤 아이디어? 감사!널 포인터 예외 자바

private void loadInstructors() 
{ 
    // get all account numbers from database 
    try 
    { 
    //myResultSet = myStatement.executeQuery("SELECT DISTINCT lastname FROM InstEval"); 
    myResultSet = myStatement.executeQuery("SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL"); 
    // add account numbers to accountNumberJComboBox 
    while (myResultSet.next()) 
    { 
     //instructorComboBox.addItem(myResultSet.getString("lastname")); 
     TeamsComboBox.addItem(myResultSet.getString("TEAMNAME")); 
    } 
    myResultSet.close(); // close myResultSet 
    } // end try 
    catch (SQLException exception) 
    { 
    exception.printStackTrace(); 
    } 
} 
+4

NPE에는 줄 번호가 들어있는 * stack-trace *가 있어야합니다. 귀하의 코드에서 어떤 라인이 해당합니까? –

+0

NPE가 어디에서 일어나는지 알려줄 필요가 있습니다. 더 나은 아직, 디버거를 사용하십시오. –

+0

'while (myResultSet.hasNext())'이 아니겠습니까? – JonK

답변

1

다음은 원하는 것을 수행하는 한 가지 방법입니다. 참고, 나는 여기 몇 가지를 일반화하려고 시도했다. 첫째, 설명적인 메소드 이름을 사용해야합니다 (팀 이름을 원할 경우 팀 이름을 언급하십시오). 두 번째로 적절한 유형을 반환해야하며 별개의 쿼리를 수행해야합니다. 따라서 Set을 반환해야합니다. 정렬 된 집합을 선택했지만 어쨌든 필수는 아닙니다. 다음으로, 나는 Connection 객체를 메서드에 전달하기로 결정했습니다. 블록을 열 때 리소스를 닫는 것이 좋습니다. 따라서 PreparedStatementResultSet 개체 만 닫습니다. 마지막으로, 귀하의 의견을 귀하의 코드로 업데이트하지 않는다면 그들은 더 나쁘고 그다지 쓸모가 없습니다.

// I think sorting the team names is good idea, and they're distinct... 
private SortedSet<String> getTeamNames(Connection conn) { 
    // Let's use a Set! 
    SortedSet<String> teamNames = new TreeSet<String>(); 
    // get all team names from database, at least store the query in a local 
    // String variable. You should probably extract it to a properties file. 
    final String query = "SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL"; 
    PreparedStatement ps = null; 
    ResultSet rs = null; 
    try { 
    ps = conn.prepareStatement(query); 
    rs = ps.executeQuery(); 
    // add team names to teamNames 
    while (rs.next()) { 
     teamNames.add(rs.getString("TEAMNAME")); 
    } 
    } catch (SQLException e) { 
    e.printStackTrace(); 
    } finally { 
    if (rs != null) { 
     try { 
     rs.close(); 
     } catch (SQLException e) { 
     e.printStackTrace(); 
     } 
    } 
    if (ps != null) { 
     try { 
     ps.close(); 
     } catch (SQLException e) { 
     e.printStackTrace(); 
     } 
    } 
    } 
    return teamNames; 
} 
+0

고마워요! 미안하지만, getTeamNames()를 호출 할 때 parn에서 무엇을 찾고 있습니까? – user3549412

+0

@ user3549412 parn? 'java.sql.Connection'을 의미합니까? –

+0

java.sql. *;을 (를) 통해 작업하고 있다고 생각합니다. 수입? – user3549412