Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Read Operation in Python with MySQL - Read Operation in Python with MySQL

Read Operation in Python with MySQL

Posted on December 23, 2024December 23, 2024 By Rishabh saini No Comments on Read Operation in Python with MySQL

Read Operation in Python with MySQL

When working with databases, the SELECT statement is your go-to tool for extracting information. This powerful SQL command allows you to retrieve and format data, apply filters, and sort results efficiently. In this tutorial, we will explore how to use Python and MySQL together to perform read operations. From fetching all rows to applying conditions, you’ll learn how to master database queries with Python scripts.

Download New Real Time Projects :-Click here

Read Operation in Python with MySQL
Read Operation in Python with MySQL

Setting Up the Connection

Before we dive into the operations, ensure that the MySQL database is properly configured and connected. Here’s how to create a connection object in Python using the mysql.connector library:

import mysql.connector  

# Establishing the connection  
myconn = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="your_password",
    database="PythonDB"
)  

# Creating the cursor object  
cur = myconn.cursor()

Fetching All Data from a Table

The fetchall() method retrieves all rows from the result set. This is ideal for reading complete data sets from a table.

Example: Fetch All Records

try:  
    cur.execute("SELECT * FROM Employee")  # Query to fetch all rows  
    result = cur.fetchall()  # Fetching rows  

    # Iterating through the result  
    for row in result:  
        print(row)  
except:  
    myconn.rollback()  # Rollback in case of an error  
finally:  
    myconn.close()  # Closing the connection  

Output:

('John', 101, 25000.0, 201, 'New York')
('David', 103, 25000.0, 202, 'Port of Spain')
('Nick', 104, 90000.0, 201, 'New York')

Fetching Specific Columns

To retrieve specific columns, replace the * in the query with the desired column names.

Example: Fetch Name, ID, and Salary

try:  
    cur.execute("SELECT name, id, salary FROM Employee")  
    result = cur.fetchall()  

    for row in result:  
        print(row)  
except:  
    myconn.rollback()  
finally:  
    myconn.close()

Output:

('John', 101, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)

Fetching a Single Row

The fetchone() method is useful for retrieving just one row at a time.

Example: Fetch the First Record

try:  
    cur.execute("SELECT name, id, salary FROM Employee")  
    result = cur.fetchone()  # Fetching the first row  
    print(result)  
except:  
    myconn.rollback()  
finally:  
    myconn.close()  

Output:

('John', 101, 25000.0)

Formatting the Output

The fetched data is returned as a tuple, which might not be user-friendly. Formatting improves readability.

Example: Display Data in a Table-Like Format

try:  
    cur.execute("SELECT name, id, salary FROM Employee")  
    result = cur.fetchall()  

    print(f"{'Name':<10}{'ID':<5}{'Salary':<10}")  # Column headers  
    for row in result:  
        print(f"{row[0]:<10}{row[1]:<5}{row[2]:<10.2f}")  
except:  
    myconn.rollback()  
finally:  
    myconn.close()

Output:

Name      ID   Salary    
John      101  25000.00  
David     103  25000.00  
Nick      104  90000.00  

Using the WHERE Clause

Filters can be applied to the query using the WHERE clause.

Example: Fetch Names Starting with ‘J’

try:  
    cur.execute("SELECT name, id, salary FROM Employee WHERE name LIKE 'J%'")  
    result = cur.fetchall()  

    print(f"{'Name':<10}{'ID':<5}{'Salary':<10}")  
    for row in result:  
        print(f"{row[0]:<10}{row[1]:<5}{row[2]:<10.2f}")  
except:  
    myconn.rollback()  
finally:  
    myconn.close()

Output:

Name      ID   Salary    
John      101  25000.00  
John      102  25000.00  

Ordering the Results

The ORDER BY clause helps in sorting the data.

Example: Order by Name in Ascending Order

try:  
    cur.execute("SELECT name, id, salary FROM Employee ORDER BY name ASC")  
    result = cur.fetchall()  

    print(f"{'Name':<10}{'ID':<5}{'Salary':<10}")  
    for row in result:  
        print(f"{row[0]:<10}{row[1]:<5}{row[2]:<10.2f}")  
except:  
    myconn.rollback()  
finally:  
    myconn.close()

Output:

Name      ID   Salary    
David     103  25000.00  
John      101  25000.00  
Nick      104  90000.00  

Example: Order by Name in Descending Order

try:  
    cur.execute("SELECT name, id, salary FROM Employee ORDER BY name DESC")  
    result = cur.fetchall()  

    for row in result:  
        print(row)  
except:  
    myconn.rollback()  
finally:  
    myconn.close()

Output:

('Nick', 104, 90000.0)
('John', 101, 25000.0)
('David', 103, 25000.0)

PHP PROJECT:- CLICK HERE


how to connect python with mysql in command prompt
crud operations in python with source code
crud operations in python w3schools
mysql connector/python
crud operations in python using mysql
python mysql example
crud operations in python with mysql example
Read Operation in Python with MySQL
read operation in python with mysql database
read operation in python with mysql w3schools
read operation in python with mysql example

 

Post Views: 625
Python Tags:connecting to mysql in python, crud operation in django python, crud operation in mysql with python, crud operation in python, crud operations sql python, database connection in python, how to connect mysql database with python, how to connect python with mysql db, mysql connection in python, mysql database in python, Python, python crud operation with mongodb, python crud operation with mysql, python crud operation with postgresql, python mysql

Post navigation

Previous Post: AI in Programming
Next Post: Claude AI: The Next Generation AI Assistant

More Related Articles

Mastering Control Structures in Python Chapter 6: Mastering Control Structures in Python Python
Python Course Roadmap: From Basics to Advance (Day-45 Road Map) Python
Functions in Python Chapter 8: Functions in Python With free Notes Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. Python Decorators: A Comprehensive Guide
  2. How to Calculate Distance between Two Points using GEOPY
  3. Rock, Paper, Scissors Game
  4. Database Operations: UPDATE and DELETE in MySQL Using Python
  5. How to Install Django: Step-by-Step Guide
  6. Python Tkinter Canvas: A Guide to Structured Graphics in Python

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,613)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,214)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,867)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme