我当前返回了一个结果集,其中一列中的字符串值可能为null (我的意思是根本没有值)。我有一个实现如下的条件
rs = st.executeQuery(selectSQL);
output = rs.getString("column");
由于该列在数据库中可能为null,因此当该列为null时,rs.getString()
将抛出NullPointerException
。如果column为null,我希望输出是一个空字符串,如output = "";
。我也不能检查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,我希望将output[i]
定义为N/A。这个问题源于数据库中允许的column
字段为NULL。很抱歉告诉你这是一个NPE,而实际上它是一个SQLException
。
发布于 2011-05-13 19:49:11
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= "";
}
发布于 2011-05-13 19:58:26
getString()方法的说明如下所示:
the column value; if the value is SQL NULL, the value returned is null
这意味着你的问题不是字符串值是空的,而是其他对象是空的,可能是你的ResultSet,或者你关闭了连接,或者类似的东西。提供堆栈跟踪,这会有所帮助。
发布于 2017-01-14 03:40:37
我可以这样做:
String a;
if(rs.getString("column") != null)
{
a = "Hello world!";
}
else
{
a = "Bye world!";
}
https://stackoverflow.com/questions/5991360
复制相似问题