为了防止SQL注入的问题,使用PreparedStatement这一个接口,来替代Statement
Statement对sql进行了拼接
PreparedStatement对sql进行了预编译,这里采用占位符?
public class JDBCLoginSafed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("用户名:");
String username = sc.nextLine();
System.out.println("密码:");
String password = sc.nextLine();
boolean flag = login(username, password);
if(flag) {
System.out.println("登录成功");
}else {
System.out.println("用户名密码错误");
}
}
public static boolean login(String username, String password) {
if(username == null || password == null || username.length() == 0 || password.length() == 0) {
System.out.println("用户名或密码不能为空");
return false;
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet res = null;
// 注册驱动 创建数据库连接
try {
conn = JDBCUtil.getConnection();
String sql = "select * from user where username = ? and password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,username);
pstmt.setString(2,password);
res = pstmt.executeQuery();
return res.next();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.close(pstmt,conn,res);
}
return false;
}
}