Python MySQL Limit
Python基础 2022-06-06 12:58:30小码哥的IT人生shichen
Python MySQL Limit
限定结果
您可以使用 "LIMIT" 语句限制从查询返回的记录数:
示例代码:
选取 "customers" 表中的前五条记录:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
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",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)