我基本上试图检索我存储在数据库中的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);
的位置。例如,如果删除它并放置一个计数器,迭代次数就可以了。
答案 0 :(得分:1)
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);
}
原始代码中会抛出异常,因为name
和surname
都是空的,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;