📜  Python SQLite-限制

📅  最后修改于: 2020-11-07 08:58:41             🧑  作者: Mango


在获取记录时,如果您想通过特定数量限制它们,可以使用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)]