Python面向对象+MySQL数据库+异常+模块实现学生信息管理系统

#准备工作
开发环境:Python3.7
开发工具:pycharm 2019.3
用到的Python模块:pymysql ,hashlib

#程序实现
面向对象+数据库+异常+模块。用户登录实现对学生名片的增删改查显示所有学生信息

#设计数据库
数据库:information

user表:存储用户信息
	CREATE TABLE `user`  (
  			`id` int(11) PRIMARY KEY NOT NULAUTO_INCREMENT,
  			`user_name` varchar(11)  UNIQUE,
  		    `passward` varchar(256) DEFAULT NULL);

student_msg:存储学生名片信息
	CREATE TABLE `student_msg`  (
			`id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
			 `no` varchar(12)  UNIQUE  ,
			 `name` char(10) ,
			 `sex` char(2)  ENUM('男','女') DEFAULT '男',
			 `phone` varchar(11) ,
			 `class` varchar(10) ,);

#代码

#模块MySQLHelper将数据库操作封装

import pymysql
class MySQLTool(object):
	def __init__(self,host,port,database,user,pwd,charset):
		  self.host = host
		  self.port = port
		  self.database = database
		  self.user = user
		  self.pwd = pwd
		  self.charset = charset

    def __connect(self):
        #创建连接 建立游标对象
        self.conn = None
        self.cursor = None
        self.conn = pymysql.connect(host = self.host,
                               port = self.port,
                               database = self.database,
                               user = self.user,
                               password = self.pwd,
                               charset = self.charset)

        self.cursor = self.conn.cursor()

    def __close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

    #增删改
    def __cud(self,sql,params):
        rowcount = 0
        try:
            self.__connect()
            rowcount = self.cursor.execute(sql,params)
            self.conn.commit()
            self.__close()
        except Exception as e:
            print(e)
        return rowcount

    def insert(self,sql,params= []):  #插入
        return self.__cud(sql,params)

    def updata(self,sql,params = []):  #更新
        return self.__cud(sql, params)

    def delete(self,sql,params = []):  #删除
        return self.__cud(sql, params)

    def get_one(self,sql,params = []):  #查询
        try:
            self.__connect()
            self.cursor.execute(sql,params)
            result = self.cursor.fetchall()
            self.__close()
            return result
        except Exception as e:
            print(e)

#模块Domo实现用户登录注册和学生名片的增删改查

from MySQLHelper import MySQLTool
import hashlib

tool = MySQLTool('127.0.0.1',3306,'information','root','123456','utf8')
class Student():
    def add_infors(self,no,name,sex,phone,classm):
        # 添加学生名片
        try:
            sql = "insert into student_msg (no,name,sex,phone,class) values (%s,%s,%s,%s,%s)"
            lines = tool.insert(sql,[no,name,sex,phone,classm])
            assert lines,"添加失败:学号已存在 "
        except Exception as e:
            print(e)
        else:
            print("添加成功")
    def delete_infors(self,name):
        #删除学生名片
        sql = "delete from student_msg where name  = %s"
        lines = tool.delete(sql,[name])
        if lines:
            print("删除成功")
        else:
            print('删除失败:学生信息不存在')
    def find_infors(self,name):
        #查找学生名片
        try:
            sql = "select * from student_msg where name = %s "
            lines = tool.get_one(sql,[name])
            assert lines,'学生信息不存在'
        except Exception as e:
            print(e)
        return lines
    def modify_infors(self,no1,name1,sex1,phone1,classm):
        #修改学生名片
        try:
            sql = "update student_msg set no = %s,name = %s,sex = %s,phone = %s,class= %s where name =%s"
            lines = tool.updata(sql,[no1,name1,sex1,phone1,classm,name1])
            assert lines,'修改失败:输入信息超出表字段设定长度'
        except Exception as e:
              print(e)
        else:
            print("修改成功")
    def show_infors(self):
        #显示所有学生名片

        sql="select * from student_msg"
        lines = tool.get_one(sql)
        if lines==0:
            print("没有学生名片存在:请添加学生名片")
        return lines

class User():
    def __init__(self,name,pwd):
        self.name = name
        self.pwd =pwd
    def land(self):
        #用户登录
        s = hashlib.sha256()
        s.update(self.pwd.encode("utf8")) #摘要加密
        new_psw = s.hexdigest()
        sql = "select * from user where user_name = %s and passward = %s "
        lines = tool.get_one(sql,[self.name,new_psw])
        if lines:
            print("登录成功")
        else:
            print("登录失败:用户名或密码错误\n请输入正确的用户名和密码")
        return lines
    def register(self):
        #用户注册
        s = hashlib.sha256()
        s.update(self.pwd.encode("utf8"))#摘要加密
        new_psw = s.hexdigest()
        try:
            sql = "insert into user(user_name,passward) values (%s,%s)"
            lines = tool.insert(sql,[self.name,new_psw])
            assert lines,"注册失败:用户名已存在"
        except Exception as e:
            print(e)
        else:
            print("注册成功")

#模块Test_Damo在控制台输出一二级菜单并实现对学生名片信息的管理

from Damo import Student
from Damo import User

class Menu(object):     #菜单类
	def one_menu(self):
	#显示一级菜单
   		print("          学生名片管理系统          ")
        print("      1、登录   2、注册  3、退出        ")
        print()
        print()
        choice1 = int(input("请输入需要进行操作的选项序号:"))
        return choice1
    def two_menu(self):
    #显示二级菜单
        print("          学生名片管理系统          ")
        print("     1、添加新名片")
        print("     2、查找已有名片")
        print("     3、更改名片")
        print("     4、删除旧名片")
        print("     5、打印全部名片")
        print("     6、返回一级菜单")
        print("     7、退出")
        print()
        choice2 = int(input("请输入需要进行操作的选项序号:"))
        return choice2
class Test_damo(Menu):           #操作类
    def user_main_la(self):
    #用户登录操作
        print("用户登录:")
        user_name = input("请输入用户名:")
        user_pwd = input("请输入用户密码:")
        user = User(user_name, user_pwd)
        if user.land():
        	return True  #输入用户名和密码正确时返回true
    def user_main_re(self):
    #用户注册操作
        print("用户注册:")
        user_name1 = input("请输入用户名:")
        user_pwd1 = input("请输入用户密码:")
        user = User(user_name1, user_pwd1)
        user.register()
    def student_main(self):
    #学生名片操作
        op = self.two_menu()
        student = Student()
        if op == 1:
            no = input("请输入学号:")
            name = input("请输入学生姓名:")
            sex = input("请输入性别:")
            phone = input("请输入电话号码;")
            classname = input("请输入班级:")
            student.add_infors(no, name, sex, phone, classname)
        elif op == 2:
            name = input("请输入要查找的学生姓名:")
            stu = student.find_infors(name)
            if stu != ():
                print("编号      学号      姓名      性别     电话号码     班级")
                print(stu[0][0], "    ", stu[0][1], "    ", stu[0][2], "    ", stu[0][3], "    ", stu[0][4], "    ", stu[0][5])
        elif op == 3:
            name = input("请输入要修改的学生姓名:")
            if student.find_infors(name) !=():
                no = input("请输入修改学号:")
                sex = input("请输入修改性别:")
                phone = input("请输入修改电话号码:")
                classname = input("请输入修改班级:")
                student.modify_infors(no, name, sex, phone, classname)
        elif op == 4:
            name = input("请输入要删除的学生姓名:")
            student.delete_infors(name)
        elif op == 5:
            stu = student.show_infors()
            print("编号      学号      姓名      性别     电话号码     班级")
            for i in stu:
                print("{}      {}      {}      {}      {}      {}".format(i[0], i[1], i[2], i[3], i[4], i[5]))
        elif op == 6:
            return self.main()
        elif op == 7:
            exit()
    def main(self):
        while True:
            try:
                dt =self.one_menu()
            except Exception as e:
                print("输入错误:请输入选项序号!")
            else:
                if dt == 1:
                    if self.user_main_la()==True:
	                    while True:
	                        print()
	                        try:
	                            self.student_main()
	                        except Exception as e:
	                            print("输入错误:请输入选项序号!")
                elif dt == 2:
                    self.user_main_re()
                elif dt == 3:
                    exit()
test = Test_damo()
test.main()

#运行效果Python面向对象+MySQL数据库+异常+模块实现学生信息管理系统_第1张图片

你可能感兴趣的:(Python)