1

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.

Vincent Passau
  • 814
  • 8
  • 22
Ranjan
  • 33
  • 9
  • 1
    Please, save our eyes, use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) ! – Dorian Jun 25 '19 at 06:42

2 Answers2

4

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();
Vincent Passau
  • 814
  • 8
  • 22
3

You use your variable, rs, without ever giving it a value:

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

When you call rs.next(), rs will always be null, giving you a NullPointerException. You need to actually execute the query you're preparing before using your result set:

rs = pstmt.executeQuery();
Docteur
  • 1,235
  • 18
  • 34