Python MySQL LIMIT 子句用法


发布日期 : 2022-07-25 17:32:23 UTC

访问量: 10 次浏览

Python MySQL LIMIT 子句

在获取记录时,如果你想用一个特定的数字来限制它们,你可以这样做,使用 MySQL 的 LIMIT 子句。

例子

假设我们在 MySQL 中创建了一个名为 EMPLOYEE 的表,其名称为:

mysql> CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)

如果我们使用 INSERT 语句在其中插入 4 条记录,如:

mysql> INSERT INTO EMPLOYEE VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000),
   ('Mac', 'Mohan', 26, 'M', 2000);

下面的 SQL 语句使用 LIMIT 子句检索了 Employee 表中的前两条记录。

SELECT * FROM EMPLOYEE LIMIT 2;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 19   | M    | 2000   |
| Raj        | Kandukuri | 20   | M    | 7000   |
+------------+-----------+------+------+--------+
2 rows in set (0.00 sec)

使用 Python 的 LIMIT 子句

如果你在游标对象上调用 execute() 方法,通过传递 SELECT 查询和 LIMIT 子句,你可以检索到所需数量的记录。

例子

下面的 Python 例子创建并填充了一个名为 EMPLOYEE 的表,并使用 LIMIT 子句获取了其中的前两条记录。

import mysql.connector

# establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

# Creating a cursor object using the cursor() method
cursor = conn.cursor()

# Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2'''

# Executing the query
cursor.execute(sql)

# Fetching the data
result = cursor.fetchall()
print(result)

# Closing the connection
conn.close()

输出

[('Krishna', 'Sharma', 26, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

LIMIT 与 OFFSET

如果你需要限制从第 n 条记录开始的记录(而不是第 1 条),你可以这样做,使用 OFFSETLIMIT

import mysql.connector

# establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

# Creating a cursor object using the cursor() method
cursor = conn.cursor()

# Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''

# Executing the query
cursor.execute(sql)

# Fetching the data
result = cursor.fetchall()
print(result)

# Closing the connection
conn.close()

输出

[('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Mac', 'Mohan', 26, 'M', 2000.0)]