Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

DBMS Lecture 4 Stored Procedures in MySQL and Using Python to Manipulate Data (1)

The document provides an overview of stored procedures in MySQL, detailing their benefits, syntax, and practical examples for data manipulation. It also explains how to call these procedures using Python, including error handling and modifying procedures. Additionally, exercises are included to reinforce the concepts learned.

Uploaded by

glinn454
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DBMS Lecture 4 Stored Procedures in MySQL and Using Python to Manipulate Data (1)

The document provides an overview of stored procedures in MySQL, detailing their benefits, syntax, and practical examples for data manipulation. It also explains how to call these procedures using Python, including error handling and modifying procedures. Additionally, exercises are included to reinforce the concepts learned.

Uploaded by

glinn454
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Stored Procedures in MySQL and Using Python

to Manipulate Data
Dr Hung Tran and Dr Tran Duc Minh

DATCOM Lab, Faculty of Data Science and Artificial Intelligence


College of Technology
National Economics University, Vietnam
Email: hung.tran@neu.edu.vn
Mobile: 086-646-4048

1 Introduction to Stored Procedures in MySQL


A Stored Procedure is a set of SQL statements that can be stored in the
MySQL database server. It allows users to encapsulate business logic directly
within the database, improving efficiency and reducing repetitive SQL code.
Stored procedures are helpful for:
• Encapsulating complex operations and business logic.
• Improving performance by executing logic on the server-side, reducing
network latency.
• Providing a layer of security as users can execute procedures without ac-
cessing the underlying database structure.
Key Features of Stored Procedures:

• Reusability: Stored once, can be called multiple times.


• Performance: Precompiled code executes faster.
• Security: Can grant or restrict execution privileges on the procedure.

1
2 Basic Syntax of a Stored Procedure
Creating a stored procedure in MySQL requires using CREATE PROCEDURE and defining the procedure’s logic between BEGIN
and END.
DELIMITER //
CREATE PROCEDURE procedure_name ([IN|OUT|INOUT] parameter_name datatype, ...)
BEGIN
-- SQL logic goes here
END //
DELIMITER ;

• IN: An input parameter.


• OUT: An output parameter.
2

• INOUT: A parameter used for both input and output.

• DELIMITER: Changes the delimiter to allow semicolons within the procedure body.

3 Calling Stored Procedures in MySQL


To call a stored procedure, use the CALL statement:
CALL procedure_name(parameter1, parameter2, ...);

For example, calling a procedure that retrieves customer details:


CALL GetCustomerDetails(103);
4 Practical Examples of Stored Procedures
4.1 Example 1: Simple Stored Procedure
Task: Create a procedure to retrieve customer details (name, contact, phone) by customer number.
DELIMITER //
CREATE PROCEDURE GetCustomerDetails(IN cust_num INT,
OUT cust_name VARCHAR(50), OUT contact_name VARCHAR(50),
OUT phone VARCHAR(20))
BEGIN
SELECT customerName, CONCAT(contactFirstName, ’ ’, contactLastName), phone
INTO cust_name, contact_name, phone
FROM customers
WHERE customerNumber = cust_num;
END //
3

DELIMITER ;

This procedure retrieves customer details by taking cust num as an input, and returning the customer’s name, contact name,
and phone as output.

4.2 Example 2: IF-ELSE Logic in Stored Procedures


Task: Check the stock of a product to see if it is ”Sufficient” or ”Insufficient”.
DELIMITER //
CREATE PROCEDURE CheckStock(IN prod_code VARCHAR(15), OUT stock_status VARCHAR(20))
BEGIN
DECLARE stock INT;
SELECT quantityInStock INTO stock FROM products WHERE productCode = prod_code;

IF stock > 100 THEN


SET stock_status = ’Sufficient’;
ELSE
SET stock_status = ’Insufficient’;
END IF;
END //
DELIMITER ;

This procedure checks the stock level for a product and returns whether it’s sufficient or insufficient.

4.3 Example 3: Working with Multiple Outputs


Task: Summarize an order by retrieving the order date, customer name, and total amount.
DELIMITER //
CREATE PROCEDURE OrderSummary(IN order_num INT, OUT order_date DATE, OUT cust_name VARCHAR(50),
OUT total DECIMAL(10,2))
4

BEGIN
SELECT o.orderDate, c.customerName, SUM(od.quantityOrdered * od.priceEach)
INTO order_date, cust_name, total
FROM orders o
JOIN customers c ON o.customerNumber = c.customerNumber
JOIN orderdetails od ON o.orderNumber = od.orderNumber
WHERE o.orderNumber = order_num
GROUP BY o.orderNumber;
END //
DELIMITER ;

This procedure summarizes an order by calculating the total price and retrieving the order details.
5 Error Handling in Stored Procedures
Error handling ensures that stored procedures do not fail silently. MySQL provides DECLARE HANDLER to handle errors grace-
fully.
Example: Error Handling in Stored Procedures
DELIMITER //
CREATE PROCEDURE SafeOrderInsert(IN cust_num INT, IN order_num INT, IN order_date DATE, OUT result VARCHAR(50))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET result = ’Error: Unable to insert order’;
END;

INSERT INTO orders (orderNumber, orderDate, customerNumber, status)


VALUES (order_num, order_date, cust_num, ’In Process’);
5

SET result = ’Order successfully inserted’;


END //
DELIMITER ;

This procedure inserts an order, but if the customer number is invalid or any other error occurs, it gracefully returns an error
message.

6 Modifying and Dropping Stored Procedures


Modifying a Stored Procedure: To modify a stored procedure, you must drop it and recreate it.
DROP PROCEDURE IF EXISTS procedure_name;

Dropping a Stored Procedure: Use the DROP PROCEDURE command.


DROP PROCEDURE IF EXISTS procedure_name;

7 Using Python to Call Stored Procedures


Python can interact with MySQL databases, including calling stored procedures, using the mysql-connector-python library.

7.1 Installing MySQL Connector

pip install mysql-connector-python

7.2 Python Code to Call Stored Procedures


6

Task: Call the GetCustomerDetails stored procedure using Python.


import mysql.connector

def get_customer_details(customer_number):
try:
connection = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="classicmodels"
)

cursor = connection.cursor()
# Call the stored procedure
cursor.callproc(’GetCustomerDetails’, [customer_number, ’’, ’’, ’’])

# Fetch results
for result in cursor.stored_results():
output = result.fetchall()

# Display results
if output:
print(f"Customer Name: {output[0][0]}")
print(f"Contact Name: {output[0][1]}")
print(f"Phone: {output[0][2]}")

except mysql.connector.Error as err:


print(f"Error: {err}")
finally:
7

if connection.is_connected():
cursor.close()
connection.close()

# Call the function with a customer number


get_customer_details(103)

7.3 Python Code for Stock Checking Example


Task: Call the CheckStock stored procedure using Python.
def check_stock(product_code):
try:
connection = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="classicmodels"
)

cursor = connection.cursor()

# Call the stored procedure


cursor.callproc(’CheckStock’, [product_code, ’’])

# Fetch results
for result in cursor.stored_results():
output = result.fetchall()

# Display results
if output:
8

print(f"Stock status for product {product_code}: {output[0][0]}")

except mysql.connector.Error as err:


print(f"Error: {err}")
finally:
if connection.is_connected():
cursor.close()
connection.close()

# Call the function for a specific product


check_stock(’S10_1678’)
7.4 Python Code for Handling Multiple Outputs
Task: Call the OrderSummary stored procedure using Python.
def get_order_summary(order_number):
try:
connection = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="classicmodels"
)

cursor = connection.cursor()

# Call the stored procedure


9

cursor.callproc(’OrderSummary’, [order_number, ’’, ’’, ’’])

# Fetch results
for result in cursor.stored_results():
output = result.fetchall()

# Display results
if output:
print(f"Order Date: {output[0][0]}")
print(f"Customer Name: {output[0][1]}")
print(f"Total Amount: {output[0][2]}")

except mysql.connector.Error as err:


print(f"Error: {err}")
finally:
if connection.is_connected():
cursor.close()
connection.close()

# Call the function with an order number


get_order_summary(10100)
10
8 Conclusion
Stored procedures provide a powerful way to encapsulate business logic in the
database, allowing for faster execution, better security, and centralized logic
management. Combining stored procedures with Python creates an efficient
way to manipulate and retrieve data programmatically.
In this lecture, we covered:

• The basics of stored procedures in MySQL.


• Practical examples of creating, modifying, and calling stored procedures.
• Error handling within stored procedures.
• How to call stored procedures from Python for dynamic data manipula-
tion.

9 Exercises
• Exercise 1: Write a stored procedure that returns the total sales of
an employee by their employee number. Call the stored procedure using
Python.
• Exercise 2: Create a stored procedure that updates the stock for a given
product and returns whether the update was successful. Call the proce-
dure using Python and handle potential errors.

• Exercise 3: Write a stored procedure that lists all orders for a given
customer. Use Python to call the procedure and display the results.

11

You might also like