sql注入的demo

本文探讨了SQL注入的概念,并通过代码示例展示了#{id}和${id}在防止SQL注入上的差异。#{id}通过预编译的方式避免了注入风险,而${id}可能导致原始SQL语句被篡改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天研究了一下sql注入,废话不多说,直接上代码;
UserMapper

package com.liuzm.mapper;

import com.liuzm.bean.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
  
    @Select("select * from user_table where id = ${id}")
    User selectUser(String id);

    @Select("select * from user_table where id = #{id}")
    User selectUser2(String id);
}

Test测试类

package com.liuzm;

import com.liuzm.mapper.UserMapper;
import com.liuzm.service.impl.UserServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest(classes=MybatisApplication.class)
public class SqlTest {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserMapper userMapper;

    @Test
    public void test(){
        userService.DeleteUserById("1");
    }

    @Test
    public void test2(){
        userMapper.selectUser("1 or 1 = 1");
    }


    @Test
    public void test3(){
        userMapper.selectUser2("1");
    }
}

控制台打印

#在application.properties文件中加上这个sql语句输出打印到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#{}效果图
"select * from user_table where id = #{id}"
${}效果图(请忽略报错)
"select * from user_table where id = ${id}"

可以看出有明显的不同:
#{id}在经过预编后相当于问号(?),可以认为你传过去的就是一个整体值;
${id}传来是什么就是什么,我们传过去的是1 or 1 = 1 ,sql语句也就是1 or 1 = 1;有可能会改变原有的sql语句;
所以尽量使用#{};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值