Home » Python » Python Execute MySQL Stored Procedure

About Yatin

Working as a Technical Lead in the Information Technology sector where I'm primarily involved with projects based on Java/J2EE Technologies platform (such as Spring, Spring Boot, Hibernate, Redis, etc.), novel UI technologies (Angular & React), Docker, and AWS. Recently completed the AWS Solution Architect Associate Certification.

Python Execute MySQL Stored Procedure

Hello in this tutorial, we will understand how to connect to the MySQL database and call the stored procedures via python programming.

1. Introduction

To connect with MySQL in python programming we have the following modules that are commonly available and known to the developer world as all these modules adhere to the python database api specification

  • MySQL Connector Python – It is a preferred choice in the developer’s community as it is capable of executing database queries through python. It is python3 compatible and actively maintained
  • pyMySQL
  • MySQLDB
  • MySqlClient

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

1.2 Setting up MySQL Connector Python

Once the python is successfully installed on your system you can install the MySQL Connector Python using a simple pip command. You can fire the below command from the command prompt and it will successfully download the module from pypi.org and install it.

Installation command

pip install mysql-connector-python

1.3 Setting up MySQL database and PhpMyAdmin containers

To start with the tutorial, I am hoping that you have the MySQL up and running in your localhost environment. For easy setup, I have the database up and running on the docker environment. Along with the database, we will also bring up the PhpMyAdmin container to connect with the database. You can execute the below command to get the containers running on docker in minutes.

You can execute the below command to get the container running on docker in minutes.

Docker commands

docker run --name mysql -e MYSQL_ROOT_PASSWORD=password123 -e MYSQL_DATABASE=user -p 3306:3306 -d mysql

docker run --name phpmyadmin --link mysql:db -p 8089:80 -d phpmyadmin/phpMyAdmin

If everything goes well the containers would be started successfully as shown in Fig. 1. You can use the docker ps -a command to confirm that both containers are started successfully. For further information on docker basics, you can navigate to this tutorial.

python mysql stored procedure - phpmyadmin containers
Fig. 1: MySQL database and PhpMyAdmin containers on Docker

Once the PhpMyAdmin container is started successfully you can navigate to the following url – http://localhost:8089/ in the browser. Enter the login credentials as root and password123 to enter into the console. You are free to keep the mysql login credentials of your choice by changing them in the docker command for the mysql container.

2. Python Execute MySQL Stored Procedure

Before going any deeper in the practical let me walk you through a simple architecture diagram where it shows that wherein the mysql connector python module fits in the picture.

python mysql stored procedure - connection
Fig. 2: Python MySQL connection

For the MySQL connector python module to work we will supply the following attributes to the mysql from the python application i.e.

  • user – Identity user to work with the mysql database. Default mysql user is root
  • password – Credential of the identity user
  • host – Address of the database server. If running on localhost then you can either use localhost or 127.0.0.1
  • port – The port number. Default mysql port is 3306
  • database – Database to which you want to connect. It can be left blank

2.1 Prerequisite – Create SQL data

For this tutorial, we will need to create a table and populate some dummy data into it so that we can use this table for SQL operations. You can use the following SQL script. Make note that the user database was already created with the help of the docker run command for the mysql container.

User.sql

-- create database
CREATE DATABASE user;

-- use database
USE user;

-- create table
CREATE TABLE users (
    id INT NOT NULL AUTO_INCREMENT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender VARCHAR(50),
    PRIMARY KEY(id));

-- insert dummy data into a table
INSERT INTO users (first_name, last_name, email, gender) VALUES ('Engracia', 'Gwyther', 'egwyther0@redcross.org', 'F');
INSERT INTO users (first_name, last_name, email, gender) VALUES ('Ximenez', 'MacNeachtain', 'xmacneachtain1@posterous.com', 'NS');
INSERT INTO users (first_name, last_name, email, gender) VALUES ('Fitzgerald', 'Hartus', 'fhartus2@cdbaby.com', 'M');
INSERT INTO users (first_name, last_name, email, gender) VALUES ('Beniamino', 'Beirne', 'bbeirne3@engadget.com', 'F');
INSERT INTO users (first_name, last_name, email, gender) VALUES ('Adriana', 'Armal', 'aarmal4@booking.com', 'NS');

-- get all records from the table
SELECT * FROM users;

-- sql procedures
-- CALL get_users()
DELIMITER &&
CREATE PROCEDURE get_users ()
BEGIN
SELECT * FROM users;
END &&
DELIMITER ;

-- CALL get_user_by_id(11)
DELIMITER &&
CREATE PROCEDURE get_user_by_id (IN U_id INT)
BEGIN
SELECT first_name, last_name, email, gender FROM users WHERE id = U_id;
END &&
DELIMITER ;

-- CALL insert_user('Jane','Doe','jane.doe@automation.com', 'M')
DELIMITER &&
Create PROCEDURE insert_user (IN U_first_name VARCHAR(50), IN U_last_name VARCHAR(50), IN U_email Varchar(50), IN U_gender Varchar(50))
BEGIN
INSERT INTO users (first_name, last_name, email, gender) VALUES (U_first_name, U_last_name, U_email, U_gender);
END &&
DELIMITER ;

3. Code Example

Let us dive in with the programming stuff now.

3.1 Create a configuration file

Add the following code to the environment file wherein we will specify the connection and database details. You are free to change these details as per your configuration setup.

local.env

[DB]
username = root
password = password123
host = localhost
port = 3306
database = user

3.2 Reading the configuration

Add the following code to the python script which will read the configuration file created above and return the config object to be used later while connecting to the database. The script will import the configparser module for reading the configuration file. Remember to give the correct path where the local.env is created.

readdbconfig.py

import configparser
def read_db_params():
    # reading the env file
    config = configparser.ConfigParser()
    config.read('config/local.env')
    return config

3.3 Connecting to the database

Add the following code to the python script which will connect to the mysql database with the help of the mysql.connector module.

connecttomysqldb.py

# python mysql

import mysql.connector
from mysql.connector import Error

from readdbconfig import *


def connect():
    try:
        # method will read the env file and return the config object
        params = read_db_params()

        # connect to database
        # reading the database parameters from the config object
        conn = mysql.connector.connect(
            host=params.get('DB', 'host'),
            database=params.get('DB', 'database'),
            user=params.get('DB', 'username'),
            password=params.get('DB', 'password'),
            port=params.get('DB', 'port')
        )

        return conn
    except(Exception, Error) as error:
        print(error)

3.4 Executing the stored procedures

Add the following code to the python script which will connect to the mysql database with the help of the mysql.connector module and call the stored procedures.

callmysqlstoredprocedure.py

# python mysql

from connecttomysqldb import *


# executing the stored procedure to get all users
def get_users(conn):
    # creating a cursor to perform a sql operation
    cursor = conn.cursor()

    try:
        # execute the command
        cursor.callproc('get_users')

        # print results
        for result in cursor.stored_results():
            records = result.fetchall()
            if len(records) == 0:
                print('Empty table')
            else:
                # print results
                print('Printing user details')
                print('----------------------------')
                for record in records:
                    full_name = record[1] + " " + record[2]
                    print('Id = {}, Name = {}, Email = {}, Gender = {}'.format(record[0], full_name,
                                                                               record[3], record[4]))
    except(Exception, Error) as error:
        print(error)
    finally:
        if conn is not None:
            cursor.close()
            conn.close()
            print('\nConnection closed')


# executing the stored procedure to get user by id
def get_user_by_id(conn, uid):
    # creating a cursor to perform a sql operation
    cursor = conn.cursor()

    try:
        args = [uid]
        # execute the command
        cursor.callproc('get_user_by_id', args)

        # print results
        for result in cursor.stored_results():
            records = result.fetchall()
            if len(records) == 0:
                print('Empty table')
            else:
                # print results
                print('Printing user id = {} details'.format(uid))
                print('------------------------------------')
                for record in records:
                    full_name = record[0] + " " + record[1]
                    print('Name = {}, Email = {}, Gender = {}'.format(full_name, record[2], record[3]))
    except(Exception, Error) as error:
        print(error)
    finally:
        if conn is not None:
            cursor.close()
            conn.close()
            print('\nConnection closed')


# driver code
if __name__ == '__main__':
    get_users(connect())
    # get_user_by_id(connect(), 4)

4. Demo logs

The callmysqlstoredprocedure.py script will call the get_users() stored procedure to fetch the users from the table and show it on the IDE console. If not the exception message will be shown.

Demo logs

-- CALL get_users()

Printing user details
----------------------------
Id = 1, Name = Engracia Gwyther, Email = egwyther0@redcross.org, Gender = F
Id = 2, Name = Ximenez MacNeachtain, Email = xmacneachtain1@posterous.com, Gender = NS
Id = 3, Name = Fitzgerald Hartus, Email = fhartus2@cdbaby.com, Gender = M
Id = 4, Name = Beniamino Beirne, Email = bbeirne3@engadget.com, Gender = F
Id = 5, Name = Adriana Armal, Email = aarmal4@booking.com, Gender = NS

You can also call the get_user_by_id(…) stored procedure to fetch the details of a particular user. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned –

  • Introduction to mysql connector python module
  • Sample program to connect to the database with the help of mysql connector python module and execute the stored procedures

You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a python programming tutorial to connect to the database with the help of the mysql connector python module.

Download
You can download the full source code of this example here: Python Execute MySQL Stored Procedure

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments