【问题标题】:Variable can only be null at this location Resultset [duplicate]变量在此位置结果集只能为空 [重复]
【发布时间】:2019-06-25 06:24:18
【问题描述】:

我是编码新手,只想使用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();
            }
        }
    }

}

}

例外- 线程“主”java.lang.NullPointerException 中的异常 在 org.rjn.Login.main(Login.java:32)

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

【问题讨论】:

标签: java jdbc prepared-statement


【解决方案1】:

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

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

rs=pstmt.executeQuery();

【讨论】:

    【解决方案2】:

    你使用你的变量 rs,却没有给它一个值:

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

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

    rs = pstmt.executeQuery();
    

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多