变量在此位置只能为空结果集

Variable can only be null at this location Resultset

我是编码新手,只是想使用 Resultset 接口创建登录验证,但不断收到 NullPointerException。

public static void main(String[] args) {
    Connection con = null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    int id;
    String name;

    String qry="select name from jejw5.test where id=? and name=?";
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter your id");
    id=sc.nextInt();
    System.out.println("Enter your name");
    name=sc.next();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=Eagle");
        System.out.println("connection established");
        pstmt=con.prepareStatement(qry);
        pstmt.setInt(1, id);
        pstmt.setString(2, name);
        if(rs.next()) {
            int skill=rs.getInt(1);
            System.out.println(skill);
        }
        else{
            System.out.println("invalid user/PW");
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
    finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

}

异常- 线程异常 "main" java.lang.NullPointerException 在 org.rjn.Login.main(Login.java:32)

警告 - 变量 rs 在此位置只能为空。

您设置 ResultSet rs=null; 然后调用方法 rs.next() 所以,实际上,rs 只能在这个位置为 null。

您需要先执行查询,应该没问题:

rs=pstmt.executeQuery();

您使用变量 rs,但从未给它赋值:

ResultSet rs=null;
...
if(rs.next()) {
    int skill=rs.getInt(1);
    System.out.println(skill);
}

当您调用 rs.next() 时,rs 将始终为 null,给您一个 NullPointerException。在使用结果集之前,您需要实际执行正在准备的查询:

rs = pstmt.executeQuery();