📅  最后修改于: 2020-11-07 08:48:59             🧑  作者: 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)
如果通过传递SELECT查询和LIMIT子句在游标对象上调用execute()方法,则可以检索所需的记录数。
要使用Python从MYSQL数据库中删除表,请在游标对象上调用execute()方法,并将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日)开始的记录,你可以这样做,使用带有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)]