一、根据姓名模糊查询员工信息
<select id = "selectByName" resultType= "cn.test.domain.Employee">
select
id, emp_name as empName,
sex,email,birthday,address
from
t_employee
where
emp_name like #{empName}
</select>
以上方式需要在传值时加上%% 即 %张三% 手动添加通配符
<select id = "selectByName" resultType= "cn.test.domain.Employee">
select
id, emp_name as empName,
sex,email,birthday,address
from
t_employee
where
emp_name like ‘%${empName}%‘
</select>
通过$方式拼接的sql语句,不再是以占位符的形式生成sql,而是以拼接字符串的方式生成sql,这样做带来的问题:会引发sql注入的问题
既能解决sql注入又能够在位置文件中写%,可以使用mysql的函数 concat
<select id = "selectByName" resultType= "cn.test.domain.Employee">
select
id, emp_name as empName,
sex,email,birthday,address
from
t_employee
where
emp_name like concat(‘%‘,#{empName},‘%‘)
</select>
对于方式三也可使用 $ 即
emp_name like concat(‘%‘,‘${empName}‘,‘%‘)
通过输入的内容,改变原程序中的sql语句的结构,从而实现无账号登录、甚至篡改数据库
String sql = "select * from user_table where username = ‘"+username+"‘ and passwrod =‘"+password+"‘;
当上述sql 中参数输入 ‘or 1=1 -- and password =‘’ 无论输入的账号密码是什么一定会成功
- 预编译语句是什么
- 通常我们的一条sql在db接收到最终执行结果返回分为三个过程
- 词法和语义解析
- 优化sql语句,制定执行计划
- 执行并返回结果
- 所谓预编译语句就是将这类语句中的值用占位符替代,可以视为将sql语句模板化或者参数化,一般称这类语句叫做Prepared Statements
- 预编译语句的优势在于:依次编译,多次运行,省去课解析优化过程,还能防止sql注入
<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
select id, username, password, role
from user
where username = #{username,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
select id, username, password, role
from user
where username = ${username,jdbcType=VARCHAR}
and password = ${password,jdbcType=VARCHAR}
</select>
如: where username =#{username}, 如果传入的值是111,那么解析成sql的值为 where username =“111”
$将传入的数据直接显示生成在sql 中
如 where username =${username} 如果传入的值为111,那么解析成sql时的值为where username =111;
如果传入的值为 ;drop table user 则会有删表现象
$方式一般用于传入数据库对象, 例如传入表名
select id, username, password, role from user where username=? and password=?
原文:https://www.cnblogs.com/FuYublogs/p/14045539.html