Python, a powerful and versatile programming language, is widely used for various applications, including data analysis, machine learning, and web development. When it comes to working with databases, Python offers numerous libraries and frameworks that simplify the process. One such library is mysql-connector-python, which facilitates interactions with MySQL databases from Python scripts.

The latest version of Python, Python 3, is a significant improvement over its predecessors. It comes with several enhancements that make it a preferred choice for many developers. In this article, we will explore how to use Python 3 to connect with and manipulate MySQL databases.

Installation and Setup
Before we dive into using Python 3 with MySQL, we need to ensure we have the necessary libraries installed. The main library we'll use is mysql-connector-python, provided by Oracle.

To install it, you can use pip, Python's package manager. Open your terminal or command prompt and run the following command:
pip install mysql-connector-python

Verifying the Installation
Once the installation is complete, you can verify it by importing the library in a Python script. Create a new Python file and add the following code:
import mysql.connector print(mysql.connector.__version__)

When you run this script, it should print the version of the mysql-connector-python library, confirming that it's installed correctly.
Connecting to a MySQL Database
Now that we've installed the necessary library, we can connect to a MySQL database using Python. Here's a simple script that establishes a connection to a MySQL server:

import mysql.connector
db_config = {
"host": "localhost",
"user": "your_username",
"password": "your_password",
"database": "your_database"
}
connection = mysql.connector.connect(**db_config)
cursor = connection.cursor()
print("Connected to the database")
Replace the placeholders with your actual MySQL credentials and database name.





![SQL Course for Beginners [Full Course]](https://i.pinimg.com/originals/34/81/4d/34814dc07c6ca7cb3f5349a144ea5642.jpg)













Executing SQL Queries
With a successful connection, you can now interact with your database using SQL queries. Python provides a simple and intuitive API for executing these queries.
Using the cursor object
The cursor object in the mysql-connector-python library is used to execute SQL commands. Here's how you can use it to fetch data from a table:
query = "SELECT * FROM employees"
cursor.execute(query)
results = cursor.fetchall()
for row in results:
print(row)
Take note of the fetchall method, which retrieves all the rows of a query result. You can also use fetchone to get the first row and fetchmany(size) to get a specified number of rows.
Using prepared statements
When dealing with user input or parameters in your queries, it's essential to use prepared statements to prevent SQL injection attacks. Here's an example of using prepared statements with the cursor object:
emp_id = input("Enter employee ID: ")
query = "SELECT * FROM employees WHERE id = %s"
cursor.execute(query, (emp_id,))
result = cursor.fetchone()
if result:
print(result)
else:
print("No employee found with the given ID.")
In this example, the %s placeholder is replaced with the actual value of the emp_id variable when the query is executed.
Performing Database Operations
Python 3, in conjunction with the mysql-connector-python library, allows you to perform various database operations, such as creating tables, inserting data, updating records, and deleting data.
Creating a table
To create a table in your MySQL database using Python, you can use the following script:
query = '''
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
)
'''
cursor.execute(query)
print("Table created successfully")
Inserting data into a table
Inserting data into a table is equally simple. Below is a script that inserts records into the customers table:
query = "INSERT INTO customers (name, email) VALUES (%s, %s)"
values = [
("John Doe", "johndoe@example.com"),
("Jane Smith", "janesmith@example.com")
]
cursor.executemany(query, values)
connection.commit()
print(cursor.rowcount, "records inserted successfully.")
The executemany method is used to insert multiple records at once.
Handling Errors and Exceptions
In any database-related operation, it's crucial to handle potential errors and exceptions to maintain the integrity and security of your data. Below is an example of how to use try/except blocks to handle exceptions when executing SQL queries:
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully")
except mysql.connector.Error as err:
print(f"An error occurred: {err.errno} - {err.message}")
connection.rollback()
In this example, any error that occurs during the execution of a query will be caught and handled, preventing the changes from being committed to the database.
As you've seen, Python 3, together with the mysql-connector-python library, offers a powerful and efficient way to work with MySQL databases. By following the best practices highlighted in this article, you canwrite robust and secure scripts to manipulate your MySQL data with ease. Happy coding!