首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >处理结果集中的空值

处理结果集中的空值
EN

Stack Overflow用户
提问于 2011-05-13 19:43:48
回答 7查看 126.1K关注 0票数 44

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

代码语言:javascript
复制
rs = st.executeQuery(selectSQL);
output = rs.getString("column");

由于该列在数据库中可能为null,因此当该列为null时,rs.getString()将抛出NullPointerException。如果column为null,我希望输出是一个空字符串,如output = "";。我也不能检查if(rs.getString("column) != null。我该如何处理这种情况?

我真正的问题是:

代码语言:javascript
复制
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

EN

回答 7

Stack Overflow用户

发布于 2011-05-13 19:49:11

代码语言:javascript
复制
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= "";
}
票数 27
EN

Stack Overflow用户

发布于 2011-05-13 19:58:26

getString()方法的说明如下所示:

代码语言:javascript
复制
 the column value; if the value is SQL NULL, the value returned is null

这意味着你的问题不是字符串值是空的,而是其他对象是空的,可能是你的ResultSet,或者你关闭了连接,或者类似的东西。提供堆栈跟踪,这会有所帮助。

票数 8
EN

Stack Overflow用户

发布于 2017-01-14 03:40:37

我可以这样做:

代码语言:javascript
复制
String a;
if(rs.getString("column") != null)
{
    a = "Hello world!";
}
else
{
    a = "Bye world!";
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5991360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档