处理结果集中的空值

2022-09-01 00:22:22

我当前返回了一个结果集,在其中一列中,字符串值可能为空(我的意思是根本没有值)。我有一个条件来实现,如下所示

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

由于该列在数据库中可能为 null,因此当该列为 null 时,将引发 a。如果列为空,我希望输出是空字符串,如.我也无法检查。我该如何应对这种情况?rs.getString()NullPointerExceptionoutput = "";if(rs.getString("column) != null

我真正的问题:

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;

现在,如果其中一列值不包含任何值,即null,我希望定义为N / A。此问题源于数据库中允许的字段为 NULL 这一事实。很抱歉告诉您这是一个NPE,而实际上它是一个.output[i]columnSQLException


答案 1

由于该列在数据库中可能为空,因此 rs.getString() 将引发 NullPointerException()

不。

rs.getString如果该列存在于所选结果集(SELECT 查询列)中,则不会抛出 对于特定记录,如果 'comumn 的值在 db 中为 null,则必须执行类似如下操作 -NullPointer

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

您可能需要参考文档 -wasNull()

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

答案 2
output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`

if(output == null){// if you fetched null value then initialize output with blank string
  output= "";
}

推荐