Search code examples
javajdbcprepared-statement

Variable can only be null at this location Resultset


So im new to coding, just wanted to create a login validation using Resultset interface but keep getting 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();
            }
        }
    }

}

}

Exception- Exception in thread "main" java.lang.NullPointerException at org.rjn.Login.main(Login.java:32)

warning- variable rs can only be null at this location.


Solution

  • You set ResultSet rs=null; and then you call the method rs.next() so, indeed, rs can only be null at this location.

    You need to execute the query first and you should be fine :

    rs=pstmt.executeQuery();