Python MySQL LIMIT子句
在获取记录时,如果你想用一个特定的数字来限制它们,你可以这样做,使用MYSQL的LIMIT子句。
例子
假设我们在MySQL中创建了一个名为EMPLOYES的表,其名称为-
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的限制子句
如果你在游标对象上调用 execute() 方法,通过传递SELECT查询和LIMIT子句,你可以检索到所需数量的记录。
要使用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)]
LIMIT与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)]
极客教程