jdbc用sql语句使用limit分页错误

#正确代码

	@Override
	public List<Emp> findAll(int currentPage) {
		List<Emp> empList = new ArrayList<>();
		String sql ="select * from emp limit "+ (currentPage-1)*2+",2";
		ResultSet rs = jdbc.executeQuery(sql, null);
		try {
			while (rs.next()) {
				Emp emp = new Emp();
				emp.setEmpid(rs.getInt(1));
				emp.setEmpname(rs.getString(2));
				emp.setEmpsex(rs.getString(3));
				empList.add(emp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		jdbc.closeResource();
		return empList;
	}
  • 使用PreparedStatement用"?"报错原因
String sql ="select * from emp limit  (?-1)*2+,2";
//之后给?赋值不可以

错误一:limit 语句中不可以加减,然而where中可以
错误二:limit ‘1’,2;错误,传入String类型在limit中无法识别

  • 解决:使用了Statement的老办法解决。

可是这样会产生安全性的问题该怎样解决呢?

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot项目中,可以使用MyBatis作为ORM框架来实现在SQL语句分页。MyBatis提供了RowBounds类来进行分页查询,下面是实现分页查询的步骤: 1. 在MyBatis的mapper文件中编写SQL语句,例如: ``` <select id="getUserList" resultMap="userResultMap"> select * from user </select> ``` 2. 在Spring Boot项目中配置MyBatis,例如: ``` @Configuration @MapperScan("com.example.demo.mapper") public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml")); return sessionFactory; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } } ``` 3. 在mapper文件中使用RowBounds进行分页查询,例如: ``` <select id="getUserList" resultMap="userResultMap"> select * from user <where> <if test="name != null and name != ''"> and name like concat('%', #{name}, '%') </if> </where> order by id desc <if test="startIndex != null and pageSize != null"> limit #{startIndex}, #{pageSize} </if> </select> ``` 4. 在Java代码中调用mapper方法进行分页查询,例如: ``` @Autowired private UserMapper userMapper; public List<User> getUserList(String name, Integer startIndex, Integer pageSize) { RowBounds rowBounds = new RowBounds(startIndex, pageSize); return userMapper.getUserList(name, rowBounds); } ``` 其中,startIndex和pageSize是分页查询的参数,需要在mapper中使用if标签进行判断,如果有值则使用limit关键字进行分页查询。getUserList方法中使用RowBounds对象进行分页查询。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值