1

I use the code below to get all results from the database.

while(rs1.next()) {
    for(int i = 1; i < columnsNumber; i++)
        System.out.printf(rs1.getString(i)+"    ");
    System.out.println();
}

They come in form of:

1       google      com     null        
2       facebook    com     null        
3       youtube     com     null
4       bbc         com     uk

I want to not display the null value. Although still display rest of the record. Thank you!

3
  • Don't print in the case: if(rs1 == null), or add if(rs1 != null) System.out.printf(rs1.getString(i)+" ");. You may want to factor out the spaces in that case though. Commented Jan 7, 2018 at 16:54
  • You can replace null with empty string. String cell = Optional.ofNullable(rs1.getString(i)).orElse(""); System.out.printf(cell +" "); Commented Jan 7, 2018 at 16:55
  • If you don't want to print the NULL, what do you want to print instead??? Commented Jan 7, 2018 at 16:58

3 Answers 3

1

You can check for nulls with a ternary...

for(int i = 1; i < columnsNumber; i++) {
    String printMe = rs1.getString(i)
    System.out.printf(printMe == null ? "" : printMe + "\t"); 
}

In this case, if printMe (your column value) is null, it just prints an empty string. I've substituted spaces for a tab, but you can print however you like.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's exactly what I was looking for! Thank you!
0

You could do a check prior to the print:

for(int i = 1; i < columnsNumber; i++) {
    String s = rs1.getString(i)
    if (s != null) { 
       System.out.printf(s + "    "); 
    }
}
System.out.println();

Comments

0

Just do a simple null check before printing the column cell element.

while(rs1.next()) {
    for(int i = 1; i < columnsNumber; i++)
        System.out.printf(rs1.getString(i) == null ? "" : rs1.getString(i) + "\t");
    System.out.println();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.