Python MySQL 限制


在获取记录时,如果你想通过特定数量限制它们,你可以使用 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的限制子句


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

要使用 python 从 MYSQL 数据库中删除表,请调用 执行() 游标对象上的方法并将 drop 语句作为参数传递给它。

例子

下面的 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)]

限制与偏移

如果你需要限制从第 n 条记录开始的记录(不是 1 st ),你可以使用 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)]