我基本上是想将我存储在数据库中的内容检索到ArrayList。我遍历ResultSet但得到了NullPointerException

ResultSet rs = null;
ArrayList<People> peoList=null;

try {
    rs = stat.executeQuery("SELECT * from people WHERE surname='"+surname+"'");
}
catch (SQLException ex) {
    Logger.getLogger(myClass.class.getName()).log(Level.SEVERE, null, ex);
}
String name, surname;
try {
    while (rs.next()) {
        name = rs.getString("name");
        surname = rs.getString("surname");

        People peo = new People(name,surname);
        peoList.add(peo);
    }
}
catch (SQLException ex) {
    Logger.getLogger(myClass.class.getName()).log(Level.SEVERE, null, ex);
}
return peoList;


当我调用此函数时,会出现NullPinterException以及大量其他消息。我真的不明白这一点。看来问题出在我放在peoList.add(peo);的地方。例如,如果删除它并放置一个计数器,则迭代次数可以。

最佳答案

while(rs.next())
{
    name = records.getString("name");
    surname = records.getString("surname");

    People peo= new People(name,surname);
    peoList.add(peo);

}


records来自哪里?这不是您的ResultSet的变量名,而是将其命名为rs

我认为您的意思是:

while(rs.next())
{
    name = rs.getString("name");
    surname = rs.getString("surname");

    People peo= new People(name,surname);
    peoList.add(peo);

}


您的原始代码中引发了异常,因为namesurname都为空,records也是如此,因为它不存在。

UPDATE:

如前所述,您似乎还没有初始化peoList

由于风格混合等原因,您在代码上有点困难。

我重新编写了一些内容,但这是要点(包括正确初始化的peoList

final static Logger LOG = Logger.getLogger(myClass.class.getName());

ResultSet rs = null;

try {
    rs = stat.executeQuery("SELECT * from people WHERE surname='"+surname+"'");
} catch (SQLException ex) {
    LOG.severe("", ex);
}

String name, surname;
List<People> peoList = new ArrayList<People>();

try {
    while(rs.next()) {
        name = rs.getString("name");
        surname = rs.getString("surname");

        People peo= new People(name,surname);
        peoList.add(peo);

    }
} catch (SQLException ex) {
    LOG.severe("", ex);
}

return peoList;

10-04 20:51