MySQL 限制数据查询(limit)

270 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第16天,点击查看活动详情

限制数据查询 -- limit关键字

一般情况下查询出的数据是在符合条件的情况下,查询出的所有数据; 限制数据查询是在查询出的数据中限制查询结果的数量

(1)不指定初始位置(默认从第1条数据开始显示)

语法:select f1,f2,f3...
        from table_name
        where 条件
        order by ff
        limit row_count;
    说明:row_count表示显示数据的数量

例子1:查询员工表中,没有提成的所有员工

select ename,comm from t_employee
       where comm is null;

例子2:查询员工表中,没有提成的前3条数据

select ename,comm from t_employee
       where comm is null
       limit 3;

例子3:查询员工表中,工资最高的3名员工。

select ename,sal
       from t_employee
       order by sal desc
       limit 3;

在这里插入图片描述

(2)指定初始位置

语法:select f1,f2,f3...
        from table_name
        where 条件
        order by f
        limit start,row_count;
    说明:start表示初始位置,最小从0开始
          row_count表示显示数据的数量

例子:查询员工表,提成为空的员工,按照工资降序排列降序后,查看第3条到第6条数据。

select ename,sal,comm
      from t_employee
      where comm is null
      order by sal desc
      limit 2,4;

在这里插入图片描述

2表示从第3条开始查询,4表示查询4条数据

数据库中有100条数据

网页第一页5条(1~5):select... limit 0,5

网页第二页5条(6~10):select.. limit 5,5

网页第三页5条(11~15):select..limit 10,5

数据库的工具类

将常用函数封装成工具类的函数

package test;

import java.sql.Connection;
import java.sql.DriverManager;

//数据库的工具类
public class DBUtil {
	//封装一个获取数据库连接的方法
	public static Connection getCon(String dbname) throws Exception
	{
		//1. 注册加载驱动
		Class .forName("com.mysql.jdbc.Driver");
		//2.获得数据库的连接
		//(1).连接mysql的url地址
		String url="jdbc:mysql://localhost:3306/"+dbname;
		//(2).连接mysql的用户名
		String username="root";
		//(3).连接mysql的密码
		String pwd="123456";
		Connection con=DriverManager.getConnection(url, username, pwd);
		System.out.println("MySQL连接成功!"+con);
		return con;
	}