我基本上是在尝试将我存储在数据库中的内容检索到 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);
}
记录
从何而来?这不是您的 ResultSet
的变量名称,而是您将其命名为 rs
。
我想你的意思是:
while(rs.next())
{
name = rs.getString("name");
surname = rs.getString("surname");
People peo= new People(name,surname);
peoList.add(peo);
}
在您的原始代码中抛出了异常,因为 name
和 surname
都是 null,records
也是,因为它不存在。
更新:
如评论所述,您似乎还没有初始化 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;
关于java - 对象的 ResultSet 和 ArrayList 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789515/