如何检查 java 中的结果集是否为空

How to check resultset is empty or null in java

我在我的 java class (Servlet) 中有一个 sql 到 运行 的查询查询然后想做点别的。

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

我试过的

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).

我不知道我做错了什么,任何类型的帮助将不胜感激

您可以尝试修改以下行:

Statement statement = con.createStatement();

Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                          ResultSet.CONCUR_READ_ONLY);

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

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