教程上的一个代码,rs.next()报java.lang.NullPointerException,DB是封装的类,我写程序测试了一下DB类和Article也能取到数,但是运行网页就报错,是不是递归写的有问题,求各位指教!<%@page pageEncoding="GB18030"%>
<%@page import="java.sql.*,com.bjsxt.bbs.*,java.io.*,java.util.*" %>
<%!private void tree(Set<Article> articles, Connection conn, int id, int grade) {
{
String sql = "select * from article where pid = " + id;
Statement stmt = DB.createStmt(conn);
ResultSet rs = DB.executeQuery(stmt, sql); try {
while (rs.next()) {
Article a = new Article();

a.setId(rs.getInt("ID"));
a.setPid(rs.getInt("pid"));
a.setRootId(rs.getInt("RootId"));
a.setTitle(rs.getString("Title"));
a.setLeaf(rs.getInt("isleaf") == 0 ? true : false);
a.setGrade(grade);
articles.add(a);
if (!a.isLeaf()) {
tree(articles, conn, a.getId(), grade + 1);
}
}
} catch (SQLException e) {
e.printStackTrace();
} }
}%>
<%
Set<Article> articles = new HashSet<Article>();
Connection conn = DB.getConn();
tree(articles, conn, 0, 0);
DB.close(conn);                         
%> 

解决方案 »

  1.   

    ResultSet rs = stmt.executeQuery(sql);
      

  2.   

    谢谢,但我不是这么封装的,我把我封装的类贴出来!package com.bjsxt.bbs;
    import java.sql.*;
    public class DB {
    public static Connection getConn(){
    Connection conn = null;
    try {
    Class.forName("oracle.jdbc.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:bbs","bbs","bbs");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return conn;
    }

    public static Statement createStmt(Connection conn) {
    Statement stmt = null;
    try {
    stmt = conn.createStatement();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return stmt;
    } public static ResultSet executeQuery(Statement stmt, String sql) {
    ResultSet rs = null;
    try {
    rs = stmt.executeQuery(sql);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return rs;
    }
    public static void close(Connection conn) {
    if(conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    conn = null;
    }
    }

    public static void close(Statement stmt) {
    if(stmt != null) {
    try {
    stmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    stmt = null;
    }
    }

    public static void close(ResultSet rs) {
    if(rs != null) {
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    rs = null;
    }
    }

    }