How to Install MySQL and Python in Ubuntu
This guide helps you install:
Compatible with Ubuntu 18.04, 20.04, 22.04, 24.04+
Step 1: Update Your System
Before installing anything, update your system to the latest version:
Part 1: Install MySQL
Step 2: Install MySQL Server
Step 3: Secure MySQL
Run the security script:
Follow the prompts:
-
Set root password
-
Remove anonymous users
-
Disallow remote root login
-
Remove test database
-
Reload privileges
Choose Y for all.
Step 4: Check MySQL Status
To start/restart MySQL:
Step 5: Access MySQL Shell
Enter your root password to log in.
Part 2: Install Python and MySQL Connector
Step 6: Install Python 3 & pip
Python 3 is usually pre-installed. To be sure:
If needed, install Python and pip:
Step 7: Install MySQL Connector for Python
Install the official MySQL connector:
Or use PyMySQL
as an alternative:
Step 8: Test Connection with a Python Script
Create a file: mysql_test.py
Run it:
If everything is correct, you’ll see your MySQL tables printed in the terminal.
Optional: Create a New MySQL Database & User
Inside MySQL shell:
Use myuser
and mypassword
in your Python script.
Done!
You’ve successfully installed:
-
MySQL Server
-
Python 3 and pip
-
MySQL connector
-
Verified the connection with a script