Python MySQL LIMIT



  • 限制结果

    您可以使用“LIMIT”语句来限制查询返回的记录数:
    表中选择前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")
    
    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)