- Python SQLite 教程
- Python SQLite - 首頁
- Python SQLite - 簡介
- Python SQLite - 建立連線
- Python SQLite - 建立表格
- Python SQLite - 插入資料
- Python SQLite - 選擇資料
- Python SQLite - Where 子句
- Python SQLite - Order By
- Python SQLite - 更新表格
- Python SQLite - 刪除資料
- Python SQLite - 刪除表格
- Python SQLite - Limit
- Python SQLite - Join
- Python SQLite - 遊標物件
- Python SQLite 有用資源
- Python SQLite - 快速指南
- Python SQLite - 有用資源
- Python SQLite - 討論
Python SQLite - Limit
在獲取記錄時,若要透過特定數字限制這些記錄,可以使用 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)
]
廣告