How to Limit Number of Records Returned From Query in Python


In this example we will show how to limit the number of records returned from the query in Python MySQL.

Source Code

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM us_state LIMIT 6"

mycursor.execute(sql)

results = mycursor.fetchall()

for row in results:
    print(row)

mydb.close()

Output:

(0, 'Alabama', 'AL', 'Montgomery', 52420)
(1, 'Alaska', 'AK', 'Juneau', 665384)
(2, 'Arizona', 'AZ', 'Phoenix', 113990)
(3, 'Arkansas', 'AR', 'Little Rock', 53179)
(4, 'California', 'CA', 'Sacramento', 163695)
(5, 'Colorado', 'CO', 'Denver', 104094)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments