Hướng dẫn python procedures

Bài trước mình đã giới thiệu với mọi người thao tác đầy đủ CRUD trên MySQL qua Python rồi, tiếp tục bài này mình sẽ hướng dẫn mọi người cách gọi procedure trong MySQL bằng Python.

Nội dung chính

  • 1, Sử dụng phương thức execute().
  • 2, Sử dụng phương thức callproc().
  • Definition¶
  • Easy example¶
  • Example 2 - Use an argument¶
  • Example 3 - Use two arguments¶
  • Example 4 - Using a list as an argument¶
  • Example 5 - Using global variables¶
  • Key points¶
  • What is the difference between a function and a procedure in Python?
  • What is difference procedure and function?
  • What is the function in Python?
  • What are the 4 types of functions in Python?

Nội dung chính

  • 1, Sử dụng phương thức execute().
  • 2, Sử dụng phương thức callproc().
  • Definition¶
  • Easy example¶
  • Example 2 - Use an argument¶
  • Example 3 - Use two arguments¶
  • Example 4 - Using a list as an argument¶
  • Example 5 - Using global variables¶
  • Key points¶
  • What is the difference between a function and a procedure in Python?
  • What is difference procedure and function?
  • What is the function in Python?
  • What are the 4 types of functions in Python?

Để gọi được procedure thì trong database của bạn cần có procedure trước đã, ở đây mình sẽ tạo ra một procedure có tên là get_all_user để lấy ra tất cả users có trong table users.

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_all_user` ()  NO SQL
SELECT *  FROM users$$

DELIMITER ;

Tiếp đó để gọi được procedure thì mọi người có thể sử dụng một trong hai cách sau:

1, Sử dụng phương thức execute().

Đối với cách này thì mọi ngừời vẫn thực hiện như bình thường đó là truyền cú pháp gọi procedure vào trong phương thức execute().

VD:

import pymysql

connection = pymysql.connect('localhost', 'root', '', 'pymysql')

try:
    with connection.cursor() as cursor:
        
        sql = "CALL get_all_user()"
        result_count = cursor.execute(sql)

        print('Data Count: ' + str(result_count))

        print(cursor.fetchall())

finally:
    connection.close()

Kết quả trả về:

Data Count: 3

(
 (5, '[email protected]', '123456'),
 (6, '[email protected]', '123456'),
 (7, '[email protected]', '123456')
)

2, Sử dụng phương thức callproc().

Bạn cũng có thể call procedure qua phương thức callproc() với cú pháp như sau:

cursor.callproc(proc_name, args)

Trong đó:

  • proc_name là tên của procedure mà bạn muốn gọi.
  • args là một sequence chứa tham số truyền vào procedure.

VD: Mình sẽ gọi procedure get_all_user qua phương thức callproc().

import pymysql

connection = pymysql.connect('localhost', 'root', '', 'pymysql')

try:
    with connection.cursor() as cursor:

        cursor.callproc('get_all_user')

        print(cursor.fetchall())

finally:
    connection.close()

Kết quả trả về:

(
 (5, '[email protected]', '123456'),
 (6, '[email protected]', '123456'),
 (7, '[email protected]', '123456')
)
Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Bài Viết Mới

Definition¶

A procedure allows us to group a block of code under a name, known as a procedure name. We can call the block of code from anywhere in the program to execute the instructions it contains. We can also pass values to the procedure to change how it works.

Nội dung chính

  • Definition¶
  • Easy example¶
  • Example 2 - Use an argument¶
  • Example 3 - Use two arguments¶
  • Example 4 - Using a list as an argument¶
  • Example 5 - Using global variables¶
  • Key points¶
  • What is the difference between a function and a procedure in Python?
  • What is difference procedure and function?
  • What is the function in Python?
  • What are the 4 types of functions in Python?

Note

Wherever possible you should try to use procedures or functions as they tend to make your code more readable.

Easy example¶

def showMenu():
    print('Main Menu')
    print('1. Play game')
    print('2. View high scores')
    print('3. Quit')

showMenu()
Main Menu
1. Play game
2. View high scores
3. Quit

Note

showMenu() is an example of a procedure call. We can call the procedure as many times as we wish in the program.

Note

A procedure needs to be defined earlier in the program than when it is called.

Syntax¶

#define a procedure
def procedureName(arg1, arg2, ...):
    print('put instructions here')

#call the procedure
procedureName()

Examples¶

Example 2 - Use an argument¶

def storyStart(name):
    print('Once upon a time, ' + name + ' was imprisoned in a castle.')
    print('They were desperate to escape, but couldn\'t.')

userName = input('What is your name? ')

storyStart(userName)
What is your name? Joe
Once upon a time, Joe was imprisoned in a castle.
They were desperate to escape, but couldn't.

Example 3 - Use two arguments¶

The following program first creates a procedure which takes a name and gender and then correctly creates the start of a story using the correct pronouns, he or she. This procedure is used later when it is called using the information which the user inputs.

def storyStart(name, gender):
    pronoun = ''
    if gender == 'm':
        pronoun = 'He'
    elif gender == 'f':
        pronoun = 'She'

    print('Once upon a time, ' + name + ' was imprisoned in a castle.')
    print(pronoun + ' was desperate to escape, but couldn\'t.')

userName = input('What is your name? ')
gender = input('Are you male or female (type m or f)? ')

storyStart(userName, gender)
What is your name? Joe
Are you male or female (type m or f)? m
Once upon a time, Joe was imprisoned in a castle.
He was desperate to escape, but couldn't.

Example 4 - Using a list as an argument¶

def displayListAndNumber(theList):
    for i in range(len(theList)):
        itemNumber = i + 1    #This adds one to the current loop number as Python lists start at zero, but we want the shopping list to start at one.
        print(str(itemNumber) + '. ' + theList[i])
    print('---------------------')

shoppingList = ['eggs', 'milk', 'ham', 'fish', 'bread']
shoppingListHardware = ['saw', 'drill', 'wood']

displayListAndNumber(shoppingList)
displayListAndNumber(shoppingListHardware)
1. eggs
2. milk
3. ham
4. fish
5. bread
---------------------
1. saw
2. drill
3. wood
---------------------

Example 5 - Using global variables¶

pi = 3.14

def showAreaOfCircle(radius):
    area = pi * radius * radius
    print('Area: ' + str(area))

def updatePi(newPi):
    global pi
    pi = newPi

showAreaOfCircle(10)

updatePi(3.141)

showAreaOfCircle(10)

Note

We need to use the keyword global before we can change a global variable inside a procedure or function. In general you should avoid using global variables and instead pass values to procedures using arguments.

Key points¶

Hint

When you decompose a program into smaller parts, these will usually end up getting programmed in functions or procedures.

Hint

Procedures and functions are ways of abstracting your program. If you can think of parts of the program that are similar, then it is best to abstract them into their own procedure or function.

Note

Procedures and functions are both types of subroutines in programming. Both use the def keyword in Python.

What is the difference between a function and a procedure in Python?

A procedure performs a task, whereas a function produces information. Functions differ from procedures in that functions return values, unlike procedures which do not. However, parameters can be passed to both procedures and functions.

What is difference procedure and function?

Difference Between Function and Procedure.

What is the function in Python?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

What are the 4 types of functions in Python?

The following are the different types of Python Functions:.

Python Built-in Functions..

Python Recursion Functions..

Python Lambda Functions..

Python User-defined Functions..