2012-07-07 11 views
1

아래 프로그램을 개발했지만 null 포인터 예외가 발생합니다. 다음은 dao 레이어에 null 포인터 예외가 발생했습니다.

public class jdbcdaoimpl { 
    public Circle getCircle(int circleId) 
     { 
     Circle circle = null; 

     try 
     { 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","saral","saral"); 
     PreparedStatement stmt=con.prepareStatement("select * from CIRCLE where id = ?"); 
     stmt.setInt(1,circleId); 
     ResultSet rset=stmt.executeQuery(); 
     while(rset.next()) 
     { 
      circle= new Circle(circleId, rset.getString("name")); 
     }  
     rset.close(); 
     stmt.close(); 
     con.close(); 
     }     
     catch (Exception e) 
     { 
      e.printStackTrace();    
     } 
     return circle; 
    } 
} 

마지막으로 메인 클래스

..

public class jdbcDemo { 

    public static void main(String[] args) { 
     Circle c = new jdbcdaoimpl().getCircle(1); 
     System.out.println(c.getName()); 
    } 

} 

로에 알려 주시기 바랍니다 .. 아래

public class Circle { 

    private int Id; 
    public Circle(int id, String name) { 
     super(); 
     Id = id; 
     this.name = name; 
    } 
    private String name; 
    public int getId() { 
     return Id; 
    } 
    public void setId(int id) { 
     Id = id; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 

} 

는 DAO 클래스입니다 .. 모델 클래스 메인 클래스의 실행은 널 포인터 예외를 던지고있다.

+1

여기에서 오는 NPE는 무엇입니까? ST가 있니? – GETah

답변

2

DAO 방법으로 모든 예외를 삼키고 있습니다. null을 반환합니다. 또한 쿼리가 단순히 빈 결과를 반환하는 경우 null을 반환합니다.

finally의 리소스도 close 개 실패했습니다. 예외를 전파하고 처리하지 않고 전파해야합니다.

public class JdbcDaoImpl 
{ 
    public Circle getCircle(int circleId) { 
    Connection con = null; 
    try { 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     con = DriverManager.getConnection(
      "jdbc:oracle:thin:@localhost:1521:xe","saral","saral"); 
     final PreparedStatement stmt = con.prepareStatement(
      "select * from CIRCLE where id = ?"); 
     stmt.setInt(1,circleId); 
     final ResultSet rset = stmt.executeQuery(); 
     if (rset.next()) return new Circle(circleId, rset.getString("name")); 
     throw new RuntimeException("Result set is empty"); 
    } 
    catch (RuntimeException e) { throw e; } 
    catch (Exception e) { throw new RuntimeException(e); } 
    finally { try { if (con != null) con.close(); } catch (Throwable t) {} } 
    } 
} 
+0

당신이 말한 것에 대해 100 % 명확하지 않아서 내 게시물을 제안 사항으로 업데이트 해주십시오. – user1508454

관련 문제