How to Connect MySQL using Python

To connect MySQL using Python, follow the steps below:

Step 1: Install Python MySQL Connector

In order to connect to MySQL using Python, we need to first install the required driver. In this tutorial,we are going to use mysql-connector-python package.

To install the package, run the following command.

pip install mysql-connector-python

Step 2: Installing MySQL and creating Database

This is an optional step. If you already have MySQL installed, skip to the next step. Follow this tutorial to install MySQL in the Mac operating system.

Once MySQL is installed, run the following command to connect to MySQL.

mysql -u root -p

You can use your own username in the place of root.

Run this command in the MySQL shell to create a new database.

CREATE DATABASE database_name;
USE database_name;

Replace database_name with your own database.

Run this command to create a new table.

CREATE TABLE users (name VARCHAR(255), address VARCHAR(255));

Add some data to the table.

INSERT INTO users(name,address) VALUES ('Shahid', 'Mumbai');

Step 3: Connecting MySQL using Python

Copy-paste the code shown below to your editor and save it as app.py.

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="database_name"
)

cursor = mydb.cursor()

cursor.execute("SELECT * from users")

result = cursor.fetchall()

for row in result:
  print(row)

Replace the database_name with your own database name.

Run the program using the following command.

python app.py

You should be getting the output as data from your MySQL table.

This tutorial is a part of the free course – learn python from scratch. Enroll in this free course to learn Python from scratch.

Pankaj Kumar
Pankaj Kumar
Articles: 207