ResultSet 调用getString 抛出NullPointException问题的解决

在Java连接数据库时,有时候在ResultSet 调用getString (或其他类似的方法),有时候会抛出NullPointException,异常信息如下:

java.lang.NullPointerException
com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1059)
com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2719)
org.apache.jsp.delete_jsp._jspService(delete_jsp.java:110)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

但是通过debug发现ResultSet 对象不为空,这个问题就比较头疼,网上也有很多人在提问,但是大多都没有找到问题的根本原因。出现这个问题是因为多个ResultSet 使用了一个Statement或者PrepareStatement对象而导致,比如下面的代码:

Statement stat = conn.createStatement();
try {
     ResultSet rs = stat.executeQuery("select * from BbsRecord where id=" + id);
      rs.next();
      sid = rs.getInt("sid");
      ResultSet rss = stat.executeQuery("select * from bbsrecord where sid=" + sid);
      rss.last();
      if (rss.getRow() == 1) {
           if (rs.getInt("root") == 0) {  //错误报告指示的是这里
               stat.execute("update bbsrecord set leaf = 1 where id=" + sid);
               stat.execute("delete from bbsrecord where id =" + id);
               if (rs.getInt("leaf") == 0) {
                   delete(conn,id);
               }
           }
        } else {
           stat.execute("delete from bbsrecord where id =" + id);
           if (rs.getInt("leaf") == 0) {
                delete(conn, id);
           }
        }
        rs.close();
        rss.close();
} catch (SQLException e) {
     System.out.println("sql异常");
} finally {
     stat.close();
     conn.close(); 
}

 

 在上述代码中,由于第6行和第3行使用同一个Statement,导致了第9行抛出的NullPointerException异常

你可能感兴趣的:(exception)