python entry practice - student management system

Keywords: Programming Python SQL Database MySQL

Opening chapter

Recently, I have nothing to do at home and started Python language. I have been engaged in Java development, so it is easier to learn Python than to start from scratch. After learning the basic grammar, I made a student management system (necessary for university course design ~), and consolidated the python grammar. Next, I will mainly introduce this management system (the code is at the end of the article).

Learning course attached:

  1. Official course: https://docs.python.org/zh-cn/3/

  2. Liao Xuefeng's python tutorial:[ https://www.liaoxuefeng.com/wiki/1016959663602400/1017802264972000]

  3. Rookie tutorial: https://www.runoob.com/python3/python3-comment.html

text

Basic environment

Mac OS + python3 + mysql5.6 + Visual Studio Code

The above is my development environment, not all of which are necessary.

  • Mac OS, windows and linux are all ok

  • python3 download address: https://www.python.org/downloads/release/python-370/

  • mysql is not necessary. My management system uses database, so it is installed

  • It's necessary for Ide. Choosing vscode is just a personal preference. You can also choose any tool, such as pycharm (the same company as idea), nodepad + +, or even vim editor

Attached:

  1. Basic python development configuration of vscode https://code.visualstudio.com/docs

  2. A way for mac to install python3 brew install python3

  3. Install mysql driver python3 -m pip install pymysql

    (you may also see the following: Python 3 - M PIP install MySQL connector steps on several pits at the beginning of use, and then gives up this one)

Introduction to student management system

As the name implies, it is to add, delete, modify and check the students. The students' information is stored in mysql database. The main purpose of this system is to practice and consolidate the basic grammar. Therefore, it is certain that it will not be particularly rigorous in logic processing, or even consider logic problems.

python syntax used
  • loop

  • conditional branch

  • aggregate

  • Class definition

  • Function definition

  • Module management

  • Print statement

  • Notes

Code introduction

It mainly defines three classes. See the code at the end of the article for details (don't care too much about the naming style of class name, variable name and function name. Haven't seen the python code specification yet)

  1. MysqlDb operation database (add, delete, modify and query)

  2. StudentInfoPrint print student information (print single, print list)

  3. StudentSystem student management (program entry class)

summary

There is a saying that is good, and all languages are interlinked. When you are familiar with a programming language, you can learn other languages with half the effort. Of course, it takes time to master a language. The so-called introduction is to master the basic syntax. There are many advanced features in python to learn, such as IO, network programming, threading, web development, etc. In addition, only with more actual combat can we master those knowledge points. It's impossible to see them alone.

Attachment: Code

from datetime import datetime
import pymysql

'''
    //Database tool class, providing add, delete, modify and query operations
'''
class MysqlDb:

    def __init__(self, host, username, password, db_name):
       
        self.conn = pymysql.connect(
            host=host,       # Database host address
            user=username,    # Database user name
            passwd=password,   # Database password
            database=db_name # data base
        )

        self.my_cursor = self.conn.cursor()


    # Insert a piece of data
    def insertOne(self, sql, params):
        self.my_cursor.execute(sql, params)
        self.conn.commit()
        return self.my_cursor.rowcount


    # Query all
    # Todo self. Get UU cursor(). Execute (SQL) self. Get UU cursor(). Fetchall(), error reporting
    def findAll(self, sql):
        self.my_cursor.execute(sql)
        return self.my_cursor.fetchall()


    # Delete a piece of data
    def deletebyId(self, sql, id):
        self.my_cursor.execute(sql, id)
        self.conn.commit()


    # Query by parameter
    def findByParams(self, sql, params):
        self.my_cursor.execute(sql, params)
        return self.my_cursor.fetchall()


    # Update single data
    def updateOne(self, sql, params):
        self.my_cursor.execute(sql, params)
        self.conn.commit()



'''
    //Format output student information
    //You can print single or multiple
'''
class StudentInfoPrint:
    
    # Print individual student information
    def beauty_print_one(self, stu):
        print(f"\t\t{stu[0]} | {stu[1]} | {stu[2]} | {stu[3]}")


    # Print student list
    def beauty_print_list(self, student_list):
        print(f"\t\t Serial number| Full name | Gender | Birthday")
        for stu in student_list:
            self.beauty_print_one(stu)


'''
    //Student information management
'''
class StudentSystem:

    def __init__(self):
        self.data = []
        self.mysql_db = MysqlDb('localhost','root', '123456', 'student_sys')
        self.my_print = StudentInfoPrint()


    # Display menu
    def show_menu(self):    
        print("""
            -- 1.Query all students --
            -- 2.Add student information --
            -- 3.Modify student information --
            -- 4.Delete student information --
            -- 5.Query student information -- 
            -- 0.Exit system --
        """)    


    # Show all student information
    def show_all(self):
        student_list = self.mysql_db.findAll('select * from tb_student')
        self.my_print.beauty_print_list(student_list)


    # Add student information
    def add_student(self):
        name = input('Please enter your name:')
        sex = input('Please enter gender:')
        birthday = input('Please enter birthday:')

        insert_sql = 'insert into tb_student(name, sex, birthday) values(%s, %s, %s)'
        sql_params = (name, sex, birthday)
        rowcount = self.mysql_db.insertOne(insert_sql, sql_params)

        if rowcount == 1:
            print("Add success")
       

    # Query student information by student name
    def find_byname(self, keyword):
        select_sql = 'select * from tb_student where name like %s'
        student_list = self.mysql_db.findByParams(select_sql, '%'+keyword+'%')
        return student_list


    # Modify student information
    def modify_student(self):
        keyword = input('Please enter the name of the student you want to modify:')
        student_list = self.find_byname(keyword)
        if student_list:
            if len(student_list) == 1:
                student_id = student_list[0][0]
            else:
                self.my_print.beauty_print_list(student_list)
                student_id = input('Multiple results are found. Please enter the students to be modified id:  ')

            # Perform modification
            option = input('Please select the information to modify, 1. Full name | 2. Gender | 3. Birthday: ')
            if option == '1':
                keyword = input('Please enter the name you want to modify:')
                update_sql = 'update tb_student set name=%s where id=%s'
            elif option == '2':
                keyword = input('Enter the gender you want to modify:')
                update_sql = 'update tb_student set sex=%s where id=%s'
            elif option == '3':
                keyword = input('Please enter the date of birth to modify:')
                update_sql = 'update tb_student set birthday=%s where id=%s'
            
            sql_params = (keyword, student_id)
            self.mysql_db.updateOne(update_sql, sql_params)
        else:
            print('There is no such person.')


    # Delete student information
    def del_student(self):
        keyword = input('Please enter the name of the student you want to delete:')
        student_list = self.find_byname(keyword)
        if student_list:
            student_id = ''
            if len(student_list) == 1:
                student_id = student_list[0][0]
            else:
                self.my_print.beauty_print_list(student_list)
                student_id = input('To investigate multiple records, please input the students to be deleted id:  ')
            # Perform delete operation
            self.mysql_db.deletebyId('delete from tb_student where id=%s', student_id)
        else:
            print('Query result is empty!')


    # Query and print student list
    def find_and_print(self):
        name = input('Please enter the name of the student you want to query: ')
        student_list = self.find_byname(name)
        self.my_print.beauty_print_list(student_list)


    # Perform the corresponding operation
    def execute_operation(self, op):
        if op == '1':
            self.show_all()
        elif op == '2':
            self.add_student()
        elif op == '3':
            self.modify_student()
        elif op == '4':
            self.del_student()
        elif op == '5':
            self.find_and_print()
        elif op == '0':
            print('Quit')
            exit(0)


    # Start entry function
    def start(self):
        while True:
            self.show_menu()
            op = input("Please enter the sequence number of the operation to be performed: ")
            self.execute_operation(op)


if __name__ == '__main__':
    app = StudentSystem()
    app.start()

Posted by Monadoxin on Wed, 29 Jan 2020 23:53:18 -0800