DBMS Lecture 4 Stored Procedures in MySQL and Using Python to Manipulate Data (1)
DBMS Lecture 4 Stored Procedures in MySQL and Using Python to Manipulate Data (1)
to Manipulate Data
Dr Hung Tran and Dr Tran Duc Minh
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 ;
• DELIMITER: Changes the delimiter to allow semicolons within the procedure body.
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.
This procedure checks the stock level for a product and returns whether it’s sufficient or insufficient.
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;
This procedure inserts an order, but if the customer number is invalid or any other error occurs, it gracefully returns an error
message.
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]}")
if connection.is_connected():
cursor.close()
connection.close()
cursor = connection.cursor()
# Fetch results
for result in cursor.stored_results():
output = result.fetchall()
# Display results
if output:
8
cursor = connection.cursor()
# 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]}")
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