user951487
user951487

Reputation: 855

null ResultSet exception

I want to connect to oracle and get some records.

java.sql.ResultSet r = s.executeQuery("Select * from table1");
while (r.next()==true) {
    System.out.println(r.getString("column1").toString());  
      }

table1 include like that rows

I get "Exception in thread "main" java.lang.NullPointerException" error when I execute above code. How can I fix it ?

Upvotes: 3

Views: 6557

Answers (5)

NPE
NPE

Reputation: 500267

You don't say where exactly in your code the exception occurs. The most likely causes are that s is null or that r.getString("column1") returns null.

Upvotes: 2

michael667
michael667

Reputation: 3260

  1. The return value of r.getString("column1") might be null, so you will get a NullPointerException on the subsequent toString() method call. You have to check for null values before you use the return value.

  2. You don't need to to call toString() here. The getString method already returns a string.

Upvotes: 2

Jonas B
Jonas B

Reputation: 2391

If its the first line that you posted that throws the error my guess would be that the variable s is null (not initialized), but since you don't tell us exactly what line of your code throws the error its hard to tell.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500175

Well it looks like column1 doesn't have a value for one row... so getString() is returning a null reference, which you're then calling toString() on - leading to the exception. As you're calling getString() the toString() call is pointless anyway, so you could rewrite it as:

while (r.next()) {
    System.out.println(r.getString("column1"));  
}

That will then print null instead. If you want to avoid that, use:

while (r.next()) {
    String name = r.getString("column1");
    if (name != null) {
        System.out.println(name);
    }
}

Upvotes: 4

francesco.s
francesco.s

Reputation: 306

maybe you get nullpointer because row3 has null value and you're trying to "toString"-it

Upvotes: 1

Related Questions