Connecting to a MySQL database using Python involves a few
straightforward steps. Here's a comprehensive guide to help you
understand how to do it:
1. Install MySQL Connector
First, you need to install the mysql-connector-python package, which allows
Python to interface with MySQL. You can install it using pip:
bash
pip install mysql-connector-python
2. Import the MySQL Connector
In your Python script, import the necessary modules from mysql-connector-
python.
3. Establish a Connection
To establish a connection to your MySQL database, you need to provide
your database credentials (host, database name, username, and
password).
4. Create a Cursor Object
A cursor object is required to execute SQL queries.
5. Execute SQL Queries
You can execute SQL queries like creating tables, inserting data, reading
data, updating data, and deleting data.
6. Close the Connection
After performing the required operations, close the cursor and the
connection to free up resources.
Example:To Connect to DB and Display the records
#connect_mysql.py
import mysql.connector
# Establish a connection to the MySQL database
cnx = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="AIML"
)
# Create a cursor object
cursor = cnx.cursor()
# Execute a query
query = "SELECT * FROM STUDENT"
cursor.execute(query)
# Fetch and print the results
for row in cursor:
print(row)
# Close the cursor and connection
cursor.close()
cnx.close()
Example: To perform CRUD operation
#pip install mysql-connector-python
#CRUD.py
import mysql.connector
from mysql.connector import Error
def create_connection():
return mysql.connector.connect(
host='localhost',
database='AIML',
user='root',
password='root'
)
def create_table(connection):
cursor = connection.cursor()
create_table_query = """CREATE TABLE IF NOT EXISTS Employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL
)"""
cursor.execute(create_table_query)
connection.commit()
print("Table created successfully")
def create_record(connection, name, age):
cursor = connection.cursor()
sql_insert_query = """ INSERT INTO Employee (name, age) VALUES
(%s, %s)"""
cursor.execute(sql_insert_query, (name, age))
connection.commit()
print("Record inserted successfully")
def read_records(connection):
cursor = connection.cursor()
sql_select_query = """ SELECT * FROM Employee """
cursor.execute(sql_select_query)
records = cursor.fetchall()
print("Total rows are: ", len(records))
for row in records:
print("Id = ", row[0], )
print("Name = ", row[1])
print("Age = ", row[2], "\n")
def update_record(connection, record_id, name, age):
cursor = connection.cursor()
sql_update_query = """ UPDATE Employee SET name = %s, age = %s
WHERE id = %s"""
cursor.execute(sql_update_query, (name, age, record_id))
connection.commit()
print("Record updated successfully")
def delete_record(connection, record_id):
cursor = connection.cursor()
sql_delete_query = """ DELETE FROM Employee WHERE id = %s"""
cursor.execute(sql_delete_query, (record_id,))
connection.commit()
print("Record deleted successfully")
# Usage example
try:
connection = create_connection()
# Create table
create_table(connection)
# Create a new record
create_record(connection, 'John Doe', 28)
# Read records
read_records(connection)
# Update a record
update_record(connection, 1, 'Jane Doe', 30)
# Delete a record
delete_record(connection, 1)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")