Python MySQL - LIMIT 子句



在獲取記錄時,如果要限制特定數量的記錄,可以使用 MySQL 的 LIMIT 子句。

示例

假設我們在 MySQL 中建立了一個名為 EMPLOYEES 的表,如下所示:

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 子句

如果透過傳遞 SELECT 查詢和 LIMIT 子句來呼叫遊標物件的 execute() 方法,則可以檢索所需數量的記錄。

要使用 Python 從 MySQL 資料庫中刪除表,請呼叫遊標物件的 execute() 方法並將刪除語句作為引數傳遞給它。

示例

下面的 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 條記錄(不是第一條)開始限制記錄,可以使用 OFFSET 和 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 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)]
廣告