- Python SQLite Tutorial
- Python SQLite - Home
- Python SQLite - Introduction
- Python SQLite - Establishing Connection
- Python SQLite - Create Table
- Python SQLite - Insert Data
- Python SQLite - Select Data
- Python SQLite - Where Clause
- Python SQLite - Order By
- Python SQLite - Update Table
- Python SQLite - Delete Data
- Python SQLite - Drop Table
- Python SQLite - Limit
- Python SQLite - Join
- Python SQLite - Cursor Object
- Python SQLite Useful Resources
- Python SQLite - Quick Guide
- Python SQLite - Useful Resources
- Python SQLite - Discussion
Python SQLite - 限制
在获取记录时,如果您想将记录限制为特定数量,可以使用 SQLite 的 LIMIT 子句来实现。
句法
以下是 SQLite 中 LIMIT 子句的语法 -
SELECT column1, column2, columnN FROM table_name LIMIT [no of rows]
例子
假设我们使用以下查询创建了一个名为 CRICKETERS 的表 -
sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite>
如果我们使用 INSERT 语句插入 5 条记录:
sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>
以下语句使用 LIMIT 子句检索 Cricketers 表的前 3 条记录 -
sqlite> SELECT * FROM CRICKETERS LIMIT 3; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite>
如果需要限制从第 n 条记录(不是第 1条)开始的记录,可以使用 OFFSET 和 LIMIT 来实现。
sqlite> SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- -------- Kumara Sangakkara 41 Matale Srilanka Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India sqlite>
使用 Python 的 LIMIT 子句
如果通过传递 SELECT 查询和 LIMIT 子句来调用游标对象上的 execute() 方法,则可以检索所需数量的记录。
例子
以下 python 示例使用 LIMIT 子句检索 EMPLOYEE 表的前两条记录。
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 3'''
#Executing the query
cursor.execute(sql)
#Fetching the data
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
输出
[
('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Vinay', 'Battacharya', 20, 'M', 6000.0),
('Sharukh', 'Sheik', 25, 'M', 8300.0)
]