运行-jdbc 程序中的时间错误,"Before start of result set"

Run-time error in a jdbc program,"Before start of result set"

我正在尝试为以下情况编写 JDBC 程序

the client wants an automated system that ask for user authentication. After successful login a menu appears offering an option to view salary calculated. In this option, ask for user to enter number of days then it calculates salary as per the da rules.

在这个问题中,我创建了一个数据库,每个员工都有自己的唯一 ID 和密码。这是我的员工 table.

所以我做了什么:我创建了一个主 class 文件并为菜单中的每个选项单独线程,但我只在以下一个中遇到问题。虽然我已经创建了自己的用户定义异常,但如果结果集为空,则应该 运行 。但它似乎根本没有执行。 每当我尝试执行此线程“Cal_sal”时,它都会出现以下错误。

这是我的代码:

import java.sql.*;
import java.util.Scanner;

public class Cal_sal implements Runnable{
    private final int emp_id;
    private final String password;
    public Cal_sal(int emp_id, String password) {
        this.emp_id=emp_id;
        this.password=password;
    }
    Scanner input=new Scanner(System.in);
    @Override
    public void run() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment1&2","root","4556");
            PreparedStatement stmt= con.prepareStatement("select * from employee where emp_id=? and pass=?");
            stmt.setInt(1,emp_id);
            stmt.setString(2,password);
            ResultSet rs=stmt.executeQuery();
            if(rs==null) {
                throw new error("Data not found, as per provided employee id and password.");
            }
            else
            {
                String category = rs.getString(3);
                int days;
                double Tsal,DA,bsal= rs.getInt(4);
                System.out.println("Enter number of days");
                days=input.nextInt();
                DA = (days / 30) * bsal;
                switch (category)
                {
                    case "staff" -> {
                        Tsal = (20 / 100) * DA;
                        System.out.println("Total Salary for " + days + " is " + Tsal);
                    }
                    case "engineer" -> {
                        Tsal = (15 / 100) * DA;
                        System.out.println("Total Salary for " + days + " is " + Tsal);
                    }
                    case "manager" -> {
                        Tsal = (10 / 100) * DA;
                        System.out.println("Total Salary for " + days + " is " + Tsal);
                    }
                    default -> throw new error("Unknown Error Contact admin");
                }
            }
            con.close();
        } catch (SQLException | error | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }
        input.close();
    }
}

当我输入错误的 ID 或密码时,没有提供抛出用户定义的异常 error 它说 Illegal operation on empty result set. 请帮我解决这个错误。

你应该使用 rs.next() 的结果:

if (!rs.next()) {
       throw new error("Data not found, as per provided employee id and password.");
}

如果 rs.next() returns 为假,这意味着查询没有返回任何行。