Java NullPointerException occurs when traversing a non-empty recordset

Java NullPointerException occurs when traversing a non-empty recordset … here is a solution to the problem.

Java NullPointerException occurs when traversing a non-empty recordset

I run a query on the Sybase ASE and it generates a , then I iterate through it and write the contents into a ResultSetfile. Sometimes, this throws a NullPointerException, indicating ResultSet that . null However, it does this after printing out one or two records. Other times, with the exact same input, I don’t get any errors.

I can’t produce this error consistently. The error message points to one line:

output.print(rs.getString(1));

For some reason, it seems to happen when the query takes a little longer to run. So far, the return of a recordset has been very small (4 to 7 records). Sometimes I have to run the app 3 or 4 times and then the error stops as if the query is “warming up”. I ran the query manually and there didn’t seem to be any performance issues.

Thanks again!

Best Solution

Are you sure that the ResultSet is empty and not rs.getString(1)?

This is a typical Java query

preparedStatement.setLong(1, primaryKey);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next())
{
  String foo = rs.getString(1);
  if (foo != null)
    ...
}

Related Problems and Solutions