9951 explained code solutions for 126 technologies


python-mysqlHow do I use Python to fetch all records from a MySQL database?


To use Python to fetch all records from a MySQL database, you need to:

  1. Install the MySQL Connector/Python library: pip install mysql-connector-python
  2. Create a connection to the MySQL database:
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)
  1. Create a cursor object to traverse the records:
mycursor = mydb.cursor()
  1. Execute an SQL query to fetch the records:
mycursor.execute("SELECT * FROM your_table")
  1. Fetch all the records from the cursor object:
myresult = mycursor.fetchall()

for x in myresult:
  print(x)
  1. Output:
('John', 'Highway 21')
('Amy', 'Mountain 21')
('Hannah', 'Valley 345')

Helpful links

Edit this code on GitHub