How to MySQL and Python In Ubuntu

How to MySQL and Python In Ubuntu

How to Install MySQL and Python in Ubuntu

This guide helps you install:

  • MySQL Server

  • Python 3 & pip

  • MySQL Connector for Python

  • And test the connection

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:

sudo apt update sudo apt upgrade -y

Part 1: Install MySQL

Step 2: Install MySQL Server

sudo apt install mysql-server -y

Step 3: Secure MySQL

Run the security script:

sudo mysql_secure_installation

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

sudo systemctl status mysql

To start/restart MySQL:

sudo systemctl start mysql sudo systemctl restart mysql

Step 5: Access MySQL Shell

sudo mysql -u root -p

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:

python3 --version

If needed, install Python and pip:

sudo apt install python3 python3-pip -y

Step 7: Install MySQL Connector for Python

Install the official MySQL connector:

pip3 install mysql-connector-python

Or use PyMySQL as an alternative:

pip3 install pymysql

Step 8: Test Connection with a Python Script

Create a file: mysql_test.py

import mysql.connector # Connect to MySQL db = mysql.connector.connect( host="localhost", user="root", password="your_mysql_password", database="test" # replace with your DB name ) cursor = db.cursor() cursor.execute("SHOW TABLES") for table in cursor: print(table) db.close()

Run it:

python3 mysql_test.py

If everything is correct, you’ll see your MySQL tables printed in the terminal.

Optional: Create a New MySQL Database & User

Inside MySQL shell:

CREATE DATABASE testdb; CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword'; GRANT ALL PRIVILEGES ON testdb.* TO 'myuser'@'localhost'; FLUSH PRIVILEGES;

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

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close