简体   繁体   中英

ResultSet and ArrayList of objects not working

I am basically trying to retrieve to an ArrayList something i stored in my database. I iterate through ResultSet but it I get a 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;

When I call this function, a NullPinterException arises with a ton of other messages. I really don't get this. It seems that the problem is where I put peoList.add(peo); . For example, if remove this and put a counter the number of iterations is ok.

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

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

}

Where did records come from? This is not the variable name for your ResultSet , instead you named it rs .

I think you mean to do:

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

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

}

The exception is being thrown in your original code because name and surname are both null, as is records because it does not exist.

UPDATE:

As a comment mentioned, you appear to also not have initialized peoList .

You're code is a little difficult on the eyes, due to mixed style, etc.

I re-wrote some of it, but here's the gist (including a properly initialized 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM