答案:因为会引起SQL注入
什么是SQL注入
SQL注入就是将原本的SQL语句逻辑结构改变,使得SQL语句的执行结果和原本意图不一一致。
例如:
select * from t_sys_user where name = 'admin' and pasword = '123456'
实际查询时Statement语句执行会将SQL语句按照字符串拼接,结果如下:
“select * from t_sys_user where name = " +“admin” + " and pasword = " + 123456” ;
如果我们把 or 1 = 1 作为 pasword 的参数传入,Statement执行查询的时SQL变成:
"select * from t_sys_user where name = " +“admin” + " and pasword = " + “or 1 = 1” ;
根据SQL编译顺序,如果where 后面有or条件的话,则or自动会把左右的查询条件分开,“or 1 = 1” 条件永远成立, 所以,前面的where 、and 条件已经不起作用了。
如何避免SQL注入
在Mybatis中 #{} 是预编译处理, KaTeX parse error: Expected 'EOF', got '#' at position 27: …编译处理。Mybatis在处理#̲{}时,会将SQL中的#{}替…{}时,就是把${}替换成变量的值,所以编写SQL时要避免使用 ${}赋值 。