eclipse+mysql5.7版本。
报空指针错误。
但是为啥会报错?
用statement的时候就没有报错,学用preparestatement的时候就报错了。
这是为什么?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.sql.PreparedStatement;
public class test {
private static final String URL = "jdbc:mysql://localhost:3307/student";
private static final String USERNAME = "root";
private static final String PWD = "19990210";
public static void query() {
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null ;
try {
// a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.jdbc.Driver");// 加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL, USERNAME, PWD);
// c.发送sql,执行【查】
Scanner input= new Scanner(System.in);
System.out.println("请输入用户名:");
String name = input.nextLine() ;
System.out.println("请输入年龄:");
String age = input.nextLine() ;
String sql = "select count(*) from stuinfo where name= ? and age =?";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, age);
int count = -1;
try {
if(rs.next()) {
count = rs.getInt(1) ;
}
} catch (Exception e) {
e.printStackTrace();
}
if(count>0) {
System.out.println("登陆成功!");
}else {
System.out.println("登陆失败!");
}
} catch (ClassNotFoundException e) {
System.out.println("111");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();// 对象.方法
if(connection!=null)connection.close();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
query() ;
}
}