【发布时间】: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 在此位置只能为空。
【问题讨论】:
-
请保护我们的眼睛,使用try-with-resources!
标签: java jdbc prepared-statement