Python MySQL Limit
จำกัดผลลัพธ์
คุณสามารถจำกัดจำนวนระเบียนที่ส่งคืนจากการสืบค้น โดยใช้คำสั่ง "LIMIT":
ตัวอย่าง
เลือก 5 รายการแรกในตาราง "ลูกค้า":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5")
myresult = mycursor.fetchall()
for x in
myresult:
print(x)
เริ่มต้นจากตำแหน่งอื่น
หากคุณต้องการส่งคืนห้าระเบียน เริ่มจากระเบียนที่สาม คุณสามารถใช้คำสำคัญ "OFFSET":
ตัวอย่าง
เริ่มจากตำแหน่ง 3 และส่งคืน 5 รายการ:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5
OFFSET 2")
myresult = mycursor.fetchall()
for x in
myresult:
print(x)