- SQL注入问题
- Statement 和 PreparedStatement
- 步骤
- 注意
在拼接SQL时,有一些sql的特殊关键字参与字符串的拼接,会造成安全性的问题。
- 输入用户名随便,密码:a’ or ‘a’='a
- sql : select * from users where user=‘nejfrbv’ and password=‘a’ or ‘a’=‘a’;(or后面是一个恒等式)
Statement是静态sql,表示所有参数在生成sql时都是拼接好的,静态sql容易产生SQL注入问题。
PreparedStatement是预编译sql,参数使用?作为占位符,你需要在执行sql的时候给?赋上值。安全。
- 注册驱动
- 获取连接对象Connection
- 定义SQL(参数用占位符?)
- 获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql)
- 给?赋值
setXxx(参数1,参数2);参数1是?的位置编号,参数2 是赋的值 - 执行sql的时候不需要再传递参数excuteQuery
- 处理结果
public static boolean login2(String user,String password){
if (user==null||password==null){
return false;
}
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=JDBCUtils.getConn();
String sql="select * from users where user=? and password=?";
System.out.println(sql);
stmt = conn.prepareStatement(sql);
stmt.setString(1,user);
stmt.setString(2,password);
rs= stmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(stmt,conn,rs);
}
return false;
}
注意
后期都会使用PreparedStatement来完成增删改的所有操作
- 可以防止SQL注入
- 效率更高



