java - 如何在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).
我不知道我在这里做错了什么,任何帮助将不胜感激
解决方案
您可以使用next
但切换到使用 do/while 循环,如果第一次调用next
返回 true,则行指针指向结果集中的第一行,因此您必须在next
再次调用之前阅读它
if (!resultSet.next()) {
// do no data stuff
} else {
do {
//handle result set data
} while (rs.next());
}
推荐阅读
- php - 使用 WordPress,数据未插入数据库
- pact - 在合约发布到在线经纪人之前,如何在本地验证 PACT 测试?
- ruby-on-rails - ruby 版本与 gem 文件中的 rails 不匹配
- php - 通过脚本发送警报邮件
- mongodb - 如何使用 Mongo 聚合方法将一个集合字段名称加入另一个集合字段值?
- javascript - 如何在单词/字符串中将数字转换为印度系统
- gnuplot - 在gnuplot epslatex中插入度数符号
- c# - Lidgren 第二次创建服务器实例导致 System.Net.Sockets.SocketException
- wolfram-mathematica - 如何以颜色密度作为 Mathematica 中的第三个参数制作 2D 图
- file-upload - 在 sapui5 opa 测试中无法获取上传文件的文件路径