SQL注入

SQL注入

用户往传值的地方传递进来了SQL语句导致原有SQL语句的逻辑发生改变,从而达到一些非法目的.这个过程叫做SQL注入.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        
        try(Connection conn = DBUtils.getConn()){
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery("select count(*)from user where username='"+name+"' and password='"+password+"'");
            rs.next();
            int count = rs.getInt(1);
            if (count>0){
                System.out.println("登录成功");
            }else{
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

’ or ‘1’=‘1
abc’ or ‘1’='1

当输入上面内容时,会显示登录成功
使用带有预编译效果的 PreparedStatement对象可以解决SQL注入的问题
将编译SQL语句的时间点从执行时提前到了创建时, 在创建PreparedStatement对象时将SQL语句进行编译,此时用户输入的内容还没有放到SQL语句里面, 这时编译的好处是将SQL语句业务逻辑锁死, 之后再将用户输入的内容添加进去,这样原有SQL语句的逻辑就不会被用户输入的内容改动,从而避免了SQL注入的问题.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        try(Connection conn = DBUtils.getConn()){
            String sql = "select count(*) from user where username=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            //游标下移,默认没有指向
            rs.next();
            int count = rs.getInt(1);
            if (count>0){
                System.out.println("登录成功");
            }else{
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值