SQL注入,及实例说明

来源:互联网 发布:在淘宝上能买到警服吗 编辑:程序博客网 时间:2024/05/22 09:46

例如:String sql="select * from usert where name='"+usernameInput+"' and password='"+pwdinput+"'";
这句是判断当uesrname和password条件都成立时,才会显示结果。
就是用如下的字符串拼接而成

String sql="select * from usert where username='"
+usernameInput
+"' and password='"
+pwdinput

+"'";

在输入用户名hh,密码输入下面的代码,
pwd' or '1'='1
在数据库报务器相当于执行这样的SQL语句:
select * from usert where name='hh' and password='pwd' or '1'='1' ; --这个语句不管前面的条件是否成立,后面的语句总是为真,因此where 条件语句总是成立。
所以就可以跳过前面用户名和密码的判段。
这样就不安全
       //正常的SQL查询语句    
      String sql="select * from usert where name='"+userinput+"' and password='"+pwdinput+"'";
      //userinput用户输入的字符串
      String userinput="hh";
      //pwdinput接收用户输入的字符串
      String pwdinput="pwd' or '1'='1";
这种不安全的情况是在SQL语句在拼接的情况下发生

 

这了主防范这这样”SQL注入安全“可以用预编译解决:

String sql="select * from usert where name=?and password=?";
  try {
   PreparedStatement ps=conn.prepareStatement(sql);

    //用户输入

    String username="hh";

    String userpwd="8888";


    ps.setString(1, username);
    ps.setStrng(2, userpwd);
    ps.executeUpdate();
   
   ps.close();
   conn.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }

这样,不管用户输入是什么,数据库服务器总认为是一个值,而SQL语句是相同的不会重复编译,也不会编译新的SQL语句,所以不管用户怎么输入,都不会产生"SQL注入安全"

原创粉丝点击