首页 > 解决方案 > 如何在java中检查结果集是否为空或null

问题描述

我有一个sql查询要在我的 java 类 (Servlet) 中运行,如果数据库中没有该查询的数据,那么我想做什么然后想做其他事情。

简单来说,我正在检查结果集中是否没有数据而不是想做其他事情,但这不起作用

我试过的

String str = null;
    Gson gson = new Gson();
    LinkedHashMap<Object, Object> lhm = null;
    LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();

    String sql;

    try {
        Connection con = DBConnection.createConnection();
        Statement statement = con.createStatement();

        sql = "select distinct a.DISPLAYCOUNTERNAME from DISPLAYCOUNTERNAMES a,DISPLAYCOUNTER b where a.DISPLAYCOUNTERCODE=b.DISPLAYCOUNTERCODE and USERNAME='"
                + userName + "'";

        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);

        if (!resultSet.isBeforeFirst()) { // if there is no data
            lhm = new LinkedHashMap<Object, Object>();
            lhm.put("outlet", "NoData");
            mainList.add(lhm);
            str = gson.toJson(mainList);
        }

            while (resultSet.next()) { // if there is data
                lhm = new LinkedHashMap<Object, Object>();
                counterName = resultSet.getString("DISPLAYCOUNTERNAME");
                 System.out.println("counternam"+counterName);
                lhm.put("Counter name", counterName);

                mainList.add(lhm);
                str = gson.toJson(mainList);

            }


        System.out.println(str);
        response.setContentType("application/json");
        response.getWriter().write(str);

    } catch (SQLException e) {
        System.out.println("SQL Issues 2...");
        e.printStackTrace();
    }

上面的代码抛出错误为SQL Issues 2... java.sql.SQLException: This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).

我不知道我在这里做错了什么,任何帮助将不胜感激

标签: javaresultset

解决方案


您可以使用next但切换到使用 do/while 循环,如果第一次调用next返回 true,则行指针指向结果集中的第一行,因此您必须在next再次调用之前阅读它

if (!resultSet.next()) { 
   // do no data stuff
} else { 
    do { 
      //handle result set data
    } while (rs.next()); 
}

推荐阅读