Handling the null value from a resultset

Since the column may be null in the
database, the rs.getString() will
throw a NullPointerException()

No.

rs.getString will not throw NullPointer if the column is present in the selected result set (SELECT query columns)
For a particular record if value for the ‘comumn is null in db, you must do something like this –

String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
    myValue = ""; // set it to empty string as you desire.
}

You may want to refer to wasNull() documentation –

From java.sql.ResultSet
boolean wasNull() throws SQLException;

* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* @return <code>true</code> if the last column value read was SQL
*         <code>NULL</code> and <code>false</code> otherwise
* @exception SQLException if a database access error occurs or this method is 
*            called on a closed result set
*/

Leave a Comment