我有一个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).
的形式抛出错误
我不知道我在这里做错了什么,我们将不胜感激
答案 0 :(得分:0)
您可以尝试修改该行:
Statement statement = con.createStatement();
到
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
答案 1 :(得分:0)
您可以使用next
,但切换为使用do / while循环,如果对next
的第一次调用返回true,则行指针指向结果集中的第一行,因此您必须阅读在再次调用next
之前
if (!resultSet.next()) {
// do no data stuff
} else {
do {
//handle result set data
} while (rs.next());
}