一、PreparedStatement 预编译SQL执行器
由于在登陆功能中,出现任意字符都可以登录,导致该功能有“bug” ,其原因是Statement在执行的sql语句中,其参数注入sql关键字的问题,导致sql失效
可以使用Statement的子接口PreparedStatement解决sql注入异常
使用参数占位
public static boolean userLogin(String username,String password){
// 使用jdbc
// 导入jar包
// 加载驱动类
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/j2008_db?useSSL=false&serverTimezone=GMT%2B8";
//获取连接对象
conn = DriverManager.getConnection(url,"root","123456");
//执行SQL语句 对于参数使用?占位
String sql ="select * from my_user where user_name=? and user_password=?";
// 获取预编译的sql执行器
pst = conn.prepareStatement(sql);
//设置参数 : 有多少个?需要设置多少个参数 参数类型和问号的字段类型一致
pst.setString(1 , username );
pst.setString(2, password);
//执行sql语句
rs= pst.executeQuery();
if(rs.next()){
return true;
}
} catch (ClassNotFoundException e) {
e.p