【熊子q的代码乐园】用python写个健康报备记录小系统

一、前言

coding的一路上,遇到过许多问题,也写过一些代码去解决,回头看看还是有点意思的,于是乎,右手大拇指和中指交错而过,打了个“响指”,不如开篇专栏记录下~

我是熊子q,不如就叫 熊子q的代码乐园

最近寒假来啦,但是因为疫情的影响,还是要坚持每天健康报备,但是捏,身为班长,总是有几个调皮的小可爱忘记报备,然后我就要去叫小可爱,于是乎,为了记录这些小可爱,写了一个健康报备记录小系统~

喏,大概就长这样:

二、技术实现

1.概述

这里是一个小系统,因此呢我选择了最简单的界面,那就是控制台界面!虽然黑呼呼的吧,但是不挡它的强大功能!实现的功能主要是

1、添加今日未报备人员信息

2、查看未报备人员前10信息

3、查看所有未报备人员信息

2. 环境

python3、mysql、win10

3. 技术核心

这个小系统呢,主要用了两个第三方库,一是 pymysql ,python连接mysql的第三方库,很好用哦~ 二是 matplotlib ,python绘制数学图形的强大的第三方库,也是很好用!
想要运行我的代码,你可必须要有这两个库哦

4. 数据库

数据表的设计是这样滴:

样例数据:

其中info字段为日期的拼接字符串,多次的日期中间用英文逗号隔开

对啦,假如你要运行我的代码,关于数据库要做以下操作嗷:

1.创建相关数据库以及表

在你的数据库中创建一个名字为healthy的数据库,名字为stu的数据表,按设计图创建

2.修改代码中数据库的连接账号密码

这个捏,是在源代码中第一个函数getConnection()中的第一行哟,相信聪明的你一定一眼能看出来!

千呼万唤始出来,下面就是源代码了!(当 当当当 当当当当...Music~)

5. 源代码

# -*- coding: utf-8 -*-···
'''
健康报备统计
By 熊子q
'''
import os
import time
import pymysql
import matplotlib.pyplot as plt

def getConnection():
    '''获取mysql连接对象'''
    connection = pymysql.connect(host='localhost',user='root',password='12369',database='healthy')
    return connection

def closeConnection(connection):
    '''关闭mysql连接对象'''
    connection.close()

def exist(name):
    '''
    判断该学生是否在数据库中
    '''
    connection = getConnection()
    cursor = connection.cursor()
    sql1 = "select count(*) from stu where name=%s"
    cursor.execute(sql1, (name,))
    res = cursor.fetchone()
    closeConnection(connection)
    if res[0] == 0:
        return False
    else:
        return True

def add(name):
    '''
    添加一名未报备的同学到数据库
    '''
    connection = getConnection()
    cursor = connection.cursor()
    # 获取今天日期
    t = time.localtime(time.time())
    tday = str(t.tm_mon)+'.'+str(t.tm_mday)

    if exist(name):
        # 已经在数据库中,则次数加一,信息加一
        # 查询已有数据
        cursor.execute("select cnt,info from stu where name=%s",(name,))
        res = cursor.fetchone()
        cnt = str(int(res[0])+1)
        info = res[1]+','+tday
        print(cnt,info)
        # 更新数据
        try:
            cursor.execute("update stu set cnt=%s , info=%s where name=%s", (cnt, info, name,))
            connection.commit()
            print("添加成功!")
        except:
            connection.rollback()
    else:
        # 未在数据库中,添加记录
        try:
            cursor.execute("insert into stu (name, cnt, info) values(%s, %s, %s)",(name, '1', tday,))
            connection.commit()
            print("添加成功!")
        except:
            connection.rollback()
    closeConnection(connection)

def show():
    '''
    输出数据库中按次数降序排列的前十名同学信息
    '''
    connection = getConnection()
    cursor = connection.cursor()
    cursor.execute("select * from stu order by cnt  desc limit 10")
    res = cursor.fetchall()
    tplt = "{0:{3}^6}\t{1:{3}^6}\t{2:^6}"
    print(tplt.format("姓名", "未报备次数", "详细日期", chr(12288)))
    for lst in res:
        # print(f'{lst[1]:>6}{lst[2]:>10}{lst[3]:>10}')
        print(tplt.format(lst[1], lst[2], lst[3], chr(12288)))
    closeConnection(connection)


def getAll():
    '''
    获取所有学生信息
    '''
    connection = getConnection()
    cursor = connection.cursor()
    cursor.execute("select * from stu")
    res = cursor.fetchall()
    ret = [[], []]
    for t in res:
        ret[0].append(t[1])
        ret[1].append(t[2])
    closeConnection(connection)
    return ret


def showPic():
    '''将数据以折线图的形式展示'''
    ret = getAll()
    x = ret[0]
    y = ret[1]
    plt.xticks(rotation=50)
    plt.rcParams['font.sans-serif'] = ['Simhei']
    plt.plot(x, y, 'rp-', marker='o', markersize=5)
    plt.title('未报备人员统计图')
    plt.xlabel('姓名')
    plt.ylabel('未报备次数')
    plt.show()

def menu():
    '''
    主菜单函数
    '''
    print('''
    __  __           ____  __         
   / / / /__  ____ _/ / /_/ /_  __  __
  / /_/ / _ \/ __ `/ / __/ __ \/ / / /
 / __  /  __/ /_/ / / /_/ / / / /_/ / 
/_/ /_/\___/\__,_/_/\__/_/ /_/\__, /  
                             /____/                                                                                                                                                    
    ''',end='')
    print("欢迎使用报备记录系统")
    print("1.添加今日未报备人员")
    print("2.查看未报备人员前10信息")
    print("3.查看所有未报备人员信息(折线图)")
    print("4.退出这个小系统")
    choice = input()
    if choice == "1":
        print("请输入姓名(回车换行,Over结束):")
        while(1):
            name = input()
            if(name=="Over"):
                break
            else:
                add(name)
        os.system("cls")
        menu()
    elif choice=="2":
        print("信息表格(输入任意值返回主菜单):")
        show()
        c = input()
        if c:
            os.system("cls")
            menu()
    elif choice == "3":
        showPic()
    elif choice=="4":
        os.system("exit()")

if __name__ == "__main__":
    menu()

三、最后

感谢各位大大的耐心阅读~

创作不易,少侠请留步哇!人说,萍水相逢,你我遇见皆是缘分,不如点个赞再走呗。◕ᴗ◕。

posted @ 2021-01-15 13:20  熊子q  阅读(333)  评论(0编辑  收藏  举报