1. Home
  2. Languages
  3. Python
  4. Getting Started with Python and MySQL: A Beginner’s Guide

Getting Started with Python and MySQL: A Beginner’s Guide

Certainly! Here’s a detailed step-by-step guide titled "Getting Started with Python and MySQL: A Beginner’s Guide". This guide will help you set up your environment, connect Python with MySQL, and perform basic database operations.


Step 1: Install MySQL Server

For Windows:

  1. Download the MySQL Installer from the official MySQL website.
  2. Run the installer and choose the Developer Default installation option.
  3. Follow the prompts to configure your MySQL server, including setting the root password.
  4. Complete the installation and start the MySQL server.

For macOS:

  1. Download MySQL DMG installer from MySQL Downloads.
  2. Open the package and follow the setup instructions.
  3. After installation, start MySQL server via System Preferences or terminal:
    bash
    sudo /usr/local/mysql/support-files/mysql.server start

For Linux (Ubuntu):

bash
sudo apt update
sudo apt install mysql-server
sudo systemctl start mysql
sudo mysql_secure_installation


Step 2: Verify MySQL Installation

Open your terminal (or Command Prompt) and run:

bash
mysql -u root -p

Enter your password. You should see the MySQL prompt:

mysql>

Type exit to leave.


Step 3: Install Python (if not installed)

  • Download Python from python.org.
  • Install it ensuring you check the "Add Python to PATH" option on Windows.
  • Verify installation by running:

bash
python –version


Step 4: Install MySQL Connector for Python

Python needs a connector library to communicate with MySQL.

Recommended library: mysql-connector-python

Run:

bash
pip install mysql-connector-python

Alternatively, you can use PyMySQL or mysqlclient, but mysql-connector-python is official and beginner-friendly.


Login to MySQL as root:

bash
mysql -u root -p

Create a new database:

sql
CREATE DATABASE mydatabase;

Create a new user and grant privileges:

sql
CREATE USER ‘myuser’@’localhost’ IDENTIFIED BY ‘mypassword’;
GRANT ALL PRIVILEGES ON mydatabase.* TO ‘myuser’@’localhost’;
FLUSH PRIVILEGES;
EXIT;


Step 6: Write Python Script to Connect to MySQL

Create a new Python file, e.g., mysql_test.py, and write the following code to connect, create a table, insert data, and query:

python
import mysql.connector
from mysql.connector import Error

try:

connection = mysql.connector.connect(
host='localhost',
database='mydatabase',
user='myuser',
password='mypassword'
)
if connection.is_connected():
print("Connected to MySQL database")
cursor = connection.cursor()
# Create a sample table
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary FLOAT NOT NULL
)
""")
# Insert sample data
cursor.execute("""
INSERT INTO employees (name, salary)
VALUES ('John Doe', 70000),
('Jane Smith', 80000)
""")
# Commit changes
connection.commit()
# Query data
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
print("Employee Records:")
for row in rows:
print(row)

except Error as e:
print(f"Error: {e}")

finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")


Step 7: Run Your Python Script

Run the script in your terminal/command prompt:

bash
python mysql_test.py

Expected output:

Connected to MySQL database
Employee Records:
(1, ‘John Doe’, 70000.0)
(2, ‘Jane Smith’, 80000.0)
MySQL connection is closed


Step 8: Troubleshooting Common Issues

  • ModuleNotFoundError: No module named ‘mysql.connector’

    • Ensure you installed the connector: pip install mysql-connector-python
    • Check your virtual environment or Python version used in terminal.

  • Connection Error: Access denied for user

    • Verify username and password.
    • Ensure user has privileges on the database.

  • MySQL Server not running

    • Start MySQL server:
    • On Windows: Use Services to start MySQL.
    • On Mac: Use System Preferences or command line.
    • On Linux: sudo systemctl start mysql

  • Port issues

    • Default MySQL port is 3306; ensure it is not blocked or used by another app.


Additional Tips

  • Use MySQL Workbench for a GUI tool to manage your MySQL databases.
  • When deploying your app, avoid hardcoding credentials; use environment variables or secure vaults.
  • Explore SQLAlchemy for powerful ORM capabilities in Python with MySQL.
  • Always close your database connections to prevent resource leaks.


You have successfully learned how to:

  • Install MySQL and Python
  • Connect Python to MySQL using mysql-connector-python
  • Create tables, insert data, and query using Python
  • Handle basic troubleshooting

This foundation will enable you to build Python applications that interact with MySQL for data storage and retrieval.

If you want me to include examples on specific CRUD operations or advanced topics, just ask!

Updated on June 3, 2025
Was this article helpful?

Related Articles

Leave a Comment