0

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

  • duplicate of https://stackoverflow.com/questions/9857257/java-jdbc-first-in-resultset-is-not-working – Gal Naor May 21 '19 at 07:14

2 Answers2

0

You can try modifying the line:

Statement statement = con.createStatement();

to

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

You could use next but switch to use a do/while loop, if the first call to next returns true then the row pointer points to the first row in the result set so you must read it before calling next again

if (!resultSet.next()) { 
   // do no data stuff
} else { 
    do { 
      //handle result set data
    } while (rs.next()); 
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52