当前位置: 代码迷 >> Java Web开发 >> jdbc解决方案
  详细解决方案

jdbc解决方案

热度:323   发布时间:2016-04-17 12:27:23.0
jdbc
Java code
    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语句块,你们像这和情况,会用什么更好的方法避免空指针?

------解决方案--------------------
这样的写法是不对的.ResultSet作为返回值,在思维逻辑上可能发生Connection不关闭或者Connection关闭导致返回的ResultSet失效的情况.我从来不会刻意避免空指针,只有在有对象参数传入的时候才会做if判断.
------解决方案--------------------
楼上兄弟正解,楼主可以考虑用List作为return
至于你说的去掉标志,程序出错,你只要在try,catch加上finally就可以,因为按照你的程序,走到catch的话,就没有返回值了
Java code
finally {  return null;}
------解决方案--------------------
你可以写个通用的增、删、改、查方法,如果用到查询时,只须调用query的方法即可,
增、删、改也是如此,去看我的资源,有jdbc一般通用方法,hibernate通用方法
还有一些框架整合的项目
  相关解决方案