如何在java中的表列中处理null值?

时间:2014-11-17 11:34:50

标签: java jdbc nullpointerexception

我从数据库表中获取值时一次又一次地获得空指针异常.....为什么它给我空指针异常?

这是我的代码:

private HashSet getPlayerList() {
        HashSet hs = new HashSet();
        String soccername = "";
        try {
            conn = ConnectionProvider.getConnection();
            rs = null;
            pstmt = null;
            String sql = "Select * from Players where deleted = false";

            if (conn != null) {
                pstmt = conn.prepareStatement(sql);
                rs = pstmt.executeQuery();

                while (rs.next()) {
                    soccername = rs.getString("soccername").trim();// this line giving exception
                    if (soccername == null || soccername.isEmpty()) {
                        soccername = rs.getString("name").trim();
                    }
                    hs.add(soccername);
                }
            }
        } catch (NamingException ex) {
            System.out.println(ex);
        } catch (SQLException ex) {
            System.out.println(ex);
        } finally {
            try {
                pstmt.close();
                rs.close();
                conn.close();
            } catch (SQLException ex) {
                System.out.println(ex);
            }
        }
        return hs;
   }

2 个答案:

答案 0 :(得分:0)

这是错误的:

soccername = rs.getString("soccername").trim();// this line giving exception
if (soccername == null || soccername.isEmpty()) {

如果rs.getString("soccername")返回null,则它必须指向NPE,因为它后跟函数trim()

更好的是:

soccername = rs.getString("soccername");
if (soccername == null || soccername.trim().isEmpty()) {

答案 1 :(得分:0)

应该是:

soccername = rs.getString("soccername");
if (soccername == null || soccername.isEmpty()) {
    soccername = rs.getString("name").trim();
} else {
    //now you are sure that soccername is not null
    soccername = soccername.trim();
}