Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

java - Handling the null value from a resultset

I currently have a result set returned, and in one of the columns the string value may be null (I mean no values at all). I have a condition to implement like following

rs = st.executeQuery(selectSQL);
output = rs.getString("column");

Since the column may be null in the database, the rs.getString() will throw a NullPointerException when the column is null. If column is null, I want the output to be an empty string like output = "";. I can't check if(rs.getString("column) != null either. How can I tackle this situation?

My real problem:

try {
    rs = st.executeQuery(sql);
    int i = 0;
    while (rs.next()) {
        output[i] = rs.getString(column);
        // column field in the database contains multiple results, but sometimes
        // may be null
        i++;
    }
} catch (SQLException e) {
    e.printStackTrace();
    // other than tracing the exception i want to fill the array too
}
return output;

Now, if one of the column values contains no value, i.e. null, I want output[i] defined as N/A. This problem stems from the fact that the column field is NULL allowed in the database. And sorry for telling you that it's a NPE, while in fact it's a SQLException.

question from:https://stackoverflow.com/questions/5991360/handling-the-null-value-from-a-resultset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
*/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...