How to Select All Records From a Table in Python MySQL


In this example we will show how to select all records from a table and display the result in Python MySQL.

Source Code

import mysql.connector

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

# get a cursor
mycursor = mydb.cursor()

# execute a query
mycursor.execute("SELECT * FROM us_state")

results = mycursor.fetchall()

for row in results:
    print(row)

# close the connection
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)
(6, 'Connecticut', 'CT', 'Hartford', 5543)
(7, 'Delaware', 'DE', 'Dover', 2489)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments