【问题标题】:null pointer exception on dao layerdao层上的空指针异常
【发布时间】:2012-07-07 14:05:21
【问题描述】:

我已经开发了下面的程序,但是它抛出了空指针异常。

下面是模型类..

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

}

请告知主类在执行时抛出空指针异常。

【问题讨论】:

  • NPE 来自哪里?你有ST吗?

标签: java jdbc nullpointerexception dao


【解决方案1】:

您正在吞噬 DAO 方法中的所有异常。它返回null。如果查询只返回一个空结果,它也会返回null

您也未能在finallyclose 您的资源。您必须传播您的异常,而不是在未经处理的情况下捕获它们。

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) {} }
  }
}

【讨论】:

  • 不是 100% 清楚您所说的内容,请您更新我的帖子并提出您的建议
猜你喜欢
  • 2014-06-10
  • 1970-01-01
  • 2021-01-19
  • 2019-07-18
  • 2013-08-12
  • 2015-03-27
  • 2019-12-09
  • 1970-01-01
相关资源
最近更新 更多