I currently have a resultset 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 column is null. If column is null, I want 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. All this problem stems from the fact that the column field is NULL allowed in the database. And sorry guys for telling you that its a NPE while in fact its SQLException...(noob here).
解决方案
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 NULL
.
* 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 wasNull
to see if the value read was
* SQL NULL
.
*
* @return true
if the last column value read was SQL
* NULL
and false
otherwise
* @exception SQLException if a database access error occurs or this method is
* called on a closed result set
*/