SQL 注入是用户利用某些系统没有对输入数据 进行充分检查,从而进行恶意破坏的行为。
* statement在在sql注入攻击问题,例如登录用户名采用 ‘or 1=1 or username=’;
* 对于防范SQL注入,可以采用 PreparedStatement取代Statement.
Statment和PreparedStatement的区别:
1. PreparedStatement是Statement的孩子
2. PreparedStatement能止SQL注入
3. PreparedStatement会对SQL语句进行预编译,以减轻数据库服务器的压力
实例代码:
1. 存在sql注入的代码
修改后的正确代码
* statement在在sql注入攻击问题,例如登录用户名采用 ‘or 1=1 or username=’;
* 对于防范SQL注入,可以采用 PreparedStatement取代Statement.
Statment和PreparedStatement的区别:
1. PreparedStatement是Statement的孩子
2. PreparedStatement能止SQL注入
3. PreparedStatement会对SQL语句进行预编译,以减轻数据库服务器的压力
实例代码:
1. 存在sql注入的代码
public void add(User user) {
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getconn();
st=conn.createStatement();
//
以
下写法注意
![图片](https://i-blog.csdnimg.cn/blog_migrate/eaf61c76f2e3bb06bbbe0db46081778a.jpeg)
String sql="insert into user(username,password,e)values('"+user.getUsername()+"','"+user.getPassword()+"')";
int num=st.executeUpdate(sql);
if(num<1){
throw new RuntimeException("用户注册失败");
//这种异常处理方式,要知道
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtils.release(conn, st, rs);
}
修改后的正确代码
public class UserDaoJdbcImpl implements UserDao {
@Override
public void add(User user) {
Connection conn=null;
//Statement st=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getconn();
String sql="insert into user(id,username,password,email,birthday,nickname) values(?,?,?,?,?,?)";
st=conn.prepareStatement(sql);
st.setString(1, user.getId());
st.setString(2, user.getUsername());
st.setString(3, user.getPassword());
st.setString(4, user.getEmail());
// st.setDate(5, (Date) user.getBirthday()) //不可以这样写,因为有可以系统中已经存在java.util.Data.
st.setDate(5, new java.sql.Date(user.getBirthday().getTime()));
st.setString(6, user.getNickname());
int num=st.executeUpdate();
//注意,此处的参数为空,
if(num<1){
throw new RuntimeException("用户注册失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtils.release(conn, st, rs);
}
}