You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查ResultSet中是否存在指定字段?以及如何修正根据文本框输入ID查询用户未找到时的提示逻辑?

问题2:优化用户查询逻辑,准确提示"User Not Found"

你的代码目前的核心问题是依赖最大ID判断用户是否存在,但实际场景中ID往往是不连续的(比如删除过记录),所以会出现ID在范围内但不存在却不提示的情况。另外直接拼接SQL字符串还存在SQL注入的风险,这是必须改进的安全问题。

优化思路:

  • 直接根据输入的ID查询用户,无需提前查询最大ID
  • 使用PreparedStatement替代字符串拼接,彻底避免SQL注入
  • 通过ResultSet.next()的返回值判断是否找到用户:返回true表示有匹配记录,false表示无结果
  • 添加基础输入校验,处理空值、非数字输入的场景

优化后的代码:

// 获取输入的ID并做基础校验
String inputId = searchEmployeeFld.getText().trim();
if (inputId.isEmpty()) {
    Alert emptyAlert = new Alert(AlertType.ERROR);
    emptyAlert.setContentText("Please enter a valid employee ID");
    emptyAlert.show();
    return;
}

// 使用PreparedStatement执行查询,避免SQL注入
String query = "SELECT empname, empgrsal FROM employee WHERE empid = ?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
    // 设置查询参数(假设empid是整数类型)
    stmt.setInt(1, Integer.parseInt(inputId));
    ResultSet rs = stmt.executeQuery();
    
    if (rs.next()) {
        // 找到匹配用户,填充界面数据
        NameFld.setText(rs.getString("empname"));
        double grossSalary = rs.getDouble("empgrsal");
        grossSalaryFld.setText(String.valueOf(grossSalary));
        
        // 计算净工资(简化写法:等价于原逻辑的 grossSalary - (grossSalary * 0.3))
        double netSalary = grossSalary * 0.7;
        netSalaryFld.setText(String.valueOf(netSalary));
    } else {
        // 未找到用户,弹出提示
        Alert notFoundAlert = new Alert(AlertType.ERROR);
        notFoundAlert.setContentText("User Not Found");
        notFoundAlert.show();
    }
} catch (NumberFormatException e) {
    // 处理输入不是数字的情况
    Alert invalidAlert = new Alert(AlertType.ERROR);
    invalidAlert.setContentText("Please enter a numeric ID");
    invalidAlert.show();
} catch (SQLException e) {
    // 处理数据库异常
    e.printStackTrace();
    Alert dbErrorAlert = new Alert(AlertType.ERROR);
    dbErrorAlert.setContentText("Database error: " + e.getMessage());
    dbErrorAlert.show();
}

关键改进点:

  1. 移除冗余查询:直接针对目标ID查询,逻辑更准确高效
  2. 安全防护:用PreparedStatement彻底避免SQL注入风险
  3. 健壮性提升:覆盖空输入、非数字输入、数据库异常等场景
  4. 准确的存在性判断:通过rs.next()直接判断是否有匹配记录,无论ID是否连续都能正确提示

内容的提问来源于stack exchange,提问作者koda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:39:07