SQL注入

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();
               // 下写法注意图片  
    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);
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值