Search code examples
javaresultset

How to check resultset is empty or null in java


I have a sql query to run in my java class (Servlet) what i am trying to do if there is no data in database for that query then want to do something else.

In simple terms i am checking if there is no data in resultset than want to do something else,but that's not working

What i have tried

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();
    }

The above code is throwing error as SQL Issues 2... java.sql.SQLException: This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).

I don't know what i am doing wrong here,any-kind of help will be appreciated


Solution

  • You can try modifying the line:

    Statement statement = con.createStatement();

    to

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