Site icon Full-Stack

How to Connect Python to a MySQL Database

Working with databases is a crucial skill in backend development, data analysis, and automation. One of the most common databases you’ll encounter is MySQL, and Python makes it simple to connect, query, and manipulate data using libraries like mysql-connector-python.

In this beginner-friendly guide, you’ll learn how to connect Python to a MySQL database, run SQL commands, and manage data effectively.

Why Use Python with MySQL?

Step 1: Install the MySQL Connector

To connect MySQL with Python, install the official MySQL connector library:

bash

Copy code

pip install mysql-connector-python

Step 2: Connect to the Database

python

Copy code

import mysql.connector

connection = mysql.connector.connect(

    host=”localhost”,

    user=”your_username”,

    password=”your_password”,

    database=”your_database”

)

print(“Connection successful!”)

Replace your_username, your_password, and your_database with your actual MySQL credentials.

Step 3: Create a Cursor and Execute Queries

python

Copy code

cursor = connection.cursor()

cursor.execute(“SELECT * FROM employees”)

for row in cursor.fetchall():

    print(row)

This retrieves all rows from the employees table.

Step 4: Insert Data into a Table

python

Copy code

query = “INSERT INTO employees (name, department) VALUES (%s, %s)”

values = (“Alice”, “HR”)

cursor.execute(query, values)

connection.commit()

print(“Data inserted successfully!”)

Always call commit() to save changes to the database.

Step 5: Close the Connection

python

Copy code

cursor.close()

connection.close()

This ensures all resources are properly released.

Error Handling Example

python

Copy code

try:

    connection = mysql.connector.connect(

        host=”localhost”,

        user=”root”,

        password=”pass”,

        database=”company”

    )

    print(“Connected to database!”)

except mysql.connector.Error as err:

    print(f”Error: {err}”)

Handling exceptions is a best practice in real-world applications.

Practice Challenge

Write a script that:

  1. Connects to a MySQL database
  2. Creates a new table
  3. Inserts sample data
  4. Queries and prints the data

This will help reinforce your learning and test your understanding

Why It Matters

Connecting Python to MySQL unlocks your ability to:

Learn More and Grow Your Skills

Ready to take your Python skills to the next level with real-world projects?

📚 Start now with structured learning paths and mentorship at
👉 https://www.thefullstack.co.in/courses/

You also like this:

What is Backend Development? A Complete Guide for Beginners [2025]

How Can SAP ERP Be Beneficial
What Are the Most Popular Backend Development Languages in 2025?

Frequently Asked Questions

What libraries do I need to connect Python to a MySQL database?

To connect Python to a MySQL database, you will need to install the mysql-connector-python library, which can be installed using pip. This library provides a standard database API for Python and allows you to execute SQL queries and retrieve data from your MySQL database. You can install it by running pip install mysql-connector-python in your terminal.

How do I import the MySQL library in my Python script?

To use the mysql-connector-python library in your Python script, you need to import it using the import statement. You can import it by adding import mysql.connector at the beginning of your script. This will allow you to use the library’s functions and classes to connect to your MySQL database.

What is the correct syntax to establish a connection to a MySQL database in Python?

The correct syntax to establish a connection to a MySQL database in Python is by using the connect() function from the mysql.connector library, which returns a connection object. You need to pass the database hostname, username, password, and database name as parameters to this function. The syntax is: cnx = mysql.connector.connect(user=’username’, password=’password’, host=’hostname’, database=’database_name).

How do I handle errors when connecting to a MySQL database in Python?

To handle errors when connecting to a MySQL database in Python, you can use a try-except block to catch any exceptions that may occur during the connection process. You can use the try block to attempt to establish a connection and the except block to handle any errors that may occur, such as authentication errors or network errors. This will allow your script to continue running even if an error occurs.

How do I close a connection to a MySQL database in Python?

To close a connection to a MySQL database in Python, you need to use the close() method of the connection object. This will release any system resources associated with the connection and prevent any further queries from being executed. You should always close the connection when you are finished using it to avoid resource leaks and improve performance.

Exit mobile version