Android Studio操作SQL Server:统计表行数遇ResultSet无当前行错误
问题解决:ResultSet无当前行错误及序列生成逻辑修正
错误原因分析
- ResultSet未定位到行:执行
executeQuery()后,ResultSet的初始光标位于第一行记录之前,直接调用rs.getString("seq")会触发"No current row in the ResultSet"错误,必须先调用rs.next()将光标移动到结果行。 - 类型比较逻辑错误:
rs.getString("seq")返回字符串类型,直接和整数0用equals()比较永远不成立,需先转为整数再判断。 - 代码冗余:日期格式化逻辑在if/else分支重复,可抽离复用。
修正后的代码
try { String sql = "SELECT COUNT(SeqID) AS seq FROM EloanApp"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); // SELECT COUNT(*)始终返回一行,调用next()定位到结果行 if (rs.next()) { // 抽离日期格式化逻辑,避免重复代码 Date currentDate = Calendar.getInstance().getTime(); @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd"); String dateStr = dateFormat.format(currentDate); int totalRows = rs.getInt("seq"); // 直接获取整数类型的计数结果 String sequence = totalRows == 0 ? "1" : String.valueOf(totalRows + 1); formattedDate = dateStr.concat(sequence); textview.setText(formattedDate); } } catch (Exception e) { Log.e("SQL Error : ", e.getMessage()); } finally { // 关闭数据库资源,避免连接泄漏 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException e) { Log.e("Resource Close Error", e.getMessage()); } }
关键修改说明
- 新增
rs.next():确保光标移动到结果行,才能正常访问列数据。 - 使用
rs.getInt("seq"):直接获取整数类型的统计结果,省去字符串转整数的步骤。 - 抽离日期格式化代码:减少冗余,提升代码可维护性。
- 添加finally块:ResultSet和Statement使用后必须关闭,防止数据库资源泄漏。
内容的提问来源于stack exchange,提问作者JeffyO
相关产品推荐
相关产品推荐

