zoukankan      html  css  js  c++  java
  • 利用PreparedStatement预防SQL注入

    1、什么是sql注入

      SQL 注入是用户利用某些系统没有对输入数据进行充分的检查,从而进行恶意破坏的行为。  

      例如登录用户名采用  ' or 1=1 or username=‘,后台数据查询语句就变成

      sql = select * from users where username='' or 1=1 or username='' and password='"+password+"'",由于sql中and的优先级比or高,所以整条查询语句等价于:

      sql = select * from users where true;这样就造成随意登录

     

    2、预防sql注入

    PreperedStatement是Statement的孩子,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避免SQL注入的问题。Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢PreparedStatement 可对SQL进行预编译,从而提高数据库的执行效率。并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。 

     1 public void add(User user) {
     2         Connection conn = null;
     3         PreparedStatement st = null;
     4         ResultSet rs = null;
     5         try{
     6             conn = JdbcUtils.getConnection();
     7             String sql = "insert into users(id,username,password,email,birthday,nickname) values(?,?,?,?,?,?)";//利用占位符
     8             st = conn.prepareStatement(sql);
     9             st.setString(1, user.getId());
    10             st.setString(2, user.getUsername());
    11             st.setString(3, user.getPassword());
    12             st.setString(4, user.getEmail());
    13             st.setDate(5, new java.sql.Date(user.getBirthday().getTime()));
    14             st.setString(6, user.getNickname());
    15             int num = st.executeUpdate();
    16             if(num<1){
    17                 throw new RuntimeException(”用户不存在");
    18             }
    19         }catch (Exception e) {
    20             throw new DaoException(e); 
    21         }finally{
    22             JdbcUtils.release(conn, st, rs);
    23         }
    24         
    25         
    26     }

     

     

  • 相关阅读:
    python闯关_Day012
    python闯关_Day010
    python闯关_Day009
    python闯关_Day008
    python闯关_Day07
    什么是PRD、MRD与BRD?
    Python中logging日志使用
    git一些常用的命令
    Python第三方库
    FastDFS分布式存储服务器安装
  • 原文地址:https://www.cnblogs.com/niuchuangfeng/p/9164003.html
Copyright © 2011-2022 走看看