gpt4 book ai didi

java - dao层空指针异常

转载 作者:行者123 更新时间:2023-11-30 04:44:33 24 4
gpt4 key购买 nike

我开发了以下程序,但它抛出空指针异常。

下面是模型类..

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

}

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

最佳答案

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

您也无法在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) {} }
}
}

关于java - dao层空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11373630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com