📜  Python MySQL-限制

📅  最后修改于: 2020-11-07 07:43:21             🧑  作者: Mango


在获取记录时,如果您想通过特定数量限制它们,可以使用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子句在游标对象上调用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 with OFFSET

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