2012-07-07 39 views
1

我已經開發了下面的程序,但它是拋出空指針異常。空指針異常在道層

下面是模型類..

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類..

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()); 
    } 

} 

請上建議主類的執行是拋出空指針異常。

+1

NPE從哪裏來?你有ST嗎? – GETah 2012-07-07 08:53:16

回答

2

您正在吞服DAO方法中的所有異常。它返回null。如果查詢只返回空結果,它也將返回null

您也無法通過close您的資源在finally。你必須傳播你的例外,不抓住他們沒有處理。

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

不是百分之百清楚你說什麼,請你用你的建議更新我的文章 – user1508454 2012-07-07 08:56:25