Read data from from MySQL using Python

To read data from a MySQL database using Python, you can use the mysql-connector-python library. Here’s an example code

import mysql.connector

# Connect to the MySQL database
cnx = mysql.connector.connect(
    host='your_host',
    user='your_user',
    password='your_password',
    database='your_database'
)

# Create a cursor object
cursor = cnx.cursor()

# Execute a SELECT query
query = "SELECT * FROM your_table"
cursor.execute(query)

# Fetch all rows from the result set
rows = cursor.fetchall()

# Iterate over the rows and print each row
for row in rows:
    print(row)

# Close the cursor and connection
cursor.close()
cnx.close()

In this example, replace 'your_host', 'your_user', 'your_password', and 'your_database' with the actual connection details for your MySQL database.

The code establishes a connection to the MySQL database using the specified host, username, password, and database name. It then creates a cursor object to execute SQL queries.

The example executes a SELECT query on the specified table ('your_table') and fetches all the rows from the result set using the fetchall() method. It then iterates over the rows and prints each row.

Finally, the cursor and connection are closed to release the resources.

Make sure to have the mysql-connector-python library installed before running this code. You can install it using pip:

pip install mysql-connector-python

Remember to handle any exceptions that may occur during the database connection or query execution for proper error handling.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech