MyBatis在Mapper中写计算式子报错

问题描述

在做分页查询,前端传值page(第几页)和rows(每页几行),然后将这两个值拼接到SQL查询语句中时出错。

### SQL: select * from t_log_login order by logId limit (? - 1) * ?,?
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(1 - 1) * 10,10' at line 6

解决方案

这里涉及一个知识点,参考Mybatis中的 ${} 和 #{}区别与用法

#{}会在值的两侧加引号变成字符串,然后再进行执行SQL,因为字符串不能进行计算,所以查询会出错。而${}是直接替换值,不会加引号,在${}中的值可以进行计算。

limit ${(pageBean.page - 1) * pageBean.rows},#{pageBean.rows}
原文地址:https://www.cnblogs.com/ast935478677/p/14817101.html