public ResultSet getList() {
ResultSet rs = null;
Statement stmt = null;
Connection con = null;
con = this.dbC.getConnection();
if (con != null) {
try {
stmt = con.createStatement();
if (stmt != null) {
rs = stmt.executeQuery("select * from user");
if (rs != null) {
return rs;
} else {
return null;
}
} else {
return null;
}
} catch (SQLException e) { e.printStackTrace();
} } else {
return null;
}
return rs; //标记

}
为什么去掉有标记的那一行,要提示程序要 有返回值,我每步差不多都有返回值?这里为了尽可能为避免空指针,用好多if-else语句块,你们像这和情况,会用什么更好的方法避免空指针?

解决方案 »

  1.   

    这样的写法是不对的.ResultSet作为返回值,在思维逻辑上可能发生Connection不关闭或者Connection关闭导致返回的ResultSet失效的情况.我从来不会刻意避免空指针,只有在有对象参数传入的时候才会做if判断.
      

  2.   

    楼上兄弟正解,楼主可以考虑用List作为return
    至于你说的去掉标志,程序出错,你只要在try,catch加上finally就可以,因为按照你的程序,走到catch的话,就没有返回值了finally {
      return null;
    }
      

  3.   

    你可以写个通用的增、删、改、查方法,如果用到查询时,只须调用query的方法即可,
    增、删、改也是如此,去看我的资源,有jdbc一般通用方法,hibernate通用方法
    还有一些框架整合的项目