#{}的执行结果: ...... car_type as carType from t_car where car_type = ? [main] DEBUG c.p.mybatis.mapper.CarMapper.selectByCarType - ==> Parameters: 新能源(String) [main] DEBUG c.p.mybatis.mapper.CarMapper.selectByCarType - <== Total: 2 ${}的执行结果: ....... car_type as carType from t_car where car_type = 新能源 [main] DEBUG c.p.mybatis.mapper.CarMapper.selectByCarType - ==> Parameters: 错误的原因: Cause: java.sql.SQLSyntaxErrorException: Unknown column '新能源' in 'where clause'
对查询的暑假进行排序时 #{}的执行结果: Preparing: select ....... from t_car order by produce_time ? Parameters: asc(String) select ....... from t_car order by produce_time 'asc' ${}的执行结果: Preparing: select ....... from t_car order by produce_time asc Parameters:
#{}和${}的区别: #{}: 底层使用PreparedStatement。特点:先进行SQL语句的编译,然后给SQL语句的占位符问号?传值。可以避免SQL注入的风险。 ${}:底层使用Statement。特点:先进行SQL语句的拼接,然后再对SQL语句进行编译。存在SQL注入的风险。 优先使用#{},这是原则。避免SQL注入的风险。 如果需要SQL语句的关键字放到SQL语句中,只能使用${},因为#{}是以值的形式放到SQL语句当中的。
2. 向SQL语句当中拼接表名,就需要使用${}
现实业务当中,可能会存在分表存储数据的情况。因为一张表存的话,数据量太大。查询效率比较低。 可以将这些数据有规律的分表存储,这样在查询的时候效率就比较高。因为扫描的数据量变少了。 日志表:专门存储日志信息的。如果t_log只有一张表,这张表中每一天都会产生很多log,慢慢的,这个表中数据会很多。 怎么解决问题? 可以每天生成一个新表。每张表以当天日期作为名称,例如: t_log_20220901 t_log_20220902 .... 你想知道某一天的日志信息怎么办? 假设今天是20220901,那么直接查:t_log_20220901的表即可。
<select id="selectAllByTable" resultType="Log">
<!--select * from t_log_#{date}-->
select * from t_log_${date}
</select>
<!--这条SQL语句因为是需要进行SQL语句的拼接,所以需要${} 如果只是想要传值的时候,则使用的是#{}的方式-->
3.批量删除:一次删除多条记录。 批量删除的SQL语句有两种写法: 第一种or:delete from t_car where id=1 or id=2 or id=3; 第二种int:delete from t_car where id in(1,2,3); 应该采用${}的方式: delete from t_car where id in(${ids}); 4.模糊查询:like 需求:根据汽车品牌进行模糊查询 select * from t_car where brand like '%奔驰%'; select * from t_car where brand like '%比亚迪%'; 第一种方案: '%${brand}%' 第二种方案:concat函数,这个是mysql数据库当中的一个函数,专门进行字符串拼接 concat('%',#{brand},'%') *第三种方案: "%"#{brand}"%"