学生信息管理系统python版


Posted in Python onOctober 17, 2018

本文实例为大家分享了python学生信息管理系统的具体代码,供大家参考,具体内容如下

#!/usr/bin/env python
# @Time  : 2018/3/30 17:37
# @Author : KiritoLiu
# @Contact : kiritoliuyhsky@gmail.com
# @Site  :
# @File  : 学生信息管理系统.py
# @Software: PyCharm
import pymysql
import datetime
import re
 
def CalAge(Date):
  #生日(年月日(数据库中的))转换为年龄
  if Date == "NULL":
    return "无"
  try:
    Date = Date.split('-')
    Birth = datetime.date(int(Date[0]), int(Date[1]), int(Date[2]))
    Today = datetime.date.today()
    if (Today.month > Birth.month):
      NextYear = datetime.date(Today.year + 1, Birth.month, Birth.day)
    elif (Today.month < Birth.month):
      NextYear = datetime.date(Today.year, Today.month + (Birth.month - Today.month), Birth.day)
    elif (Today.month == Birth.month):
      if (Today.day > Birth.day):
        NextYear = datetime.date(Today.year + 1, Birth.month, Birth.day)
      elif (Today.day < Birth.day):
        NextYear = datetime.date(Today.year, Birth.month, Today.day + (Birth.day - Today.day))
      elif (Today.day == Birth.day):
        NextYear = 0
    Age = Today.year - Birth.year
    if NextYear == 0: #如果今天就是生日
      return "%d" % (Age)
    else:
      DaysLeft = NextYear - Today
      return "%d" % (Age)
  except:
    return "错误"
 
def seesql():
  #查看学生表数据库
  db = pymysql.connect(host="localhost", user="root", password="123456", db="stu", charset="utf8")
  # 创建游标对象
  cursor = db.cursor()
  sql = "select s.sno,s.name,s.sex,s.cla,s.tel,s.birthday from stu s order by sno"
  # 用sno(学号)排序查看学生名单
  try:
    m = cursor.execute(sql)
    alist = cursor.fetchall()
    print("{:>3}|\t{:<4}\t|{}|\t{:<3}\t\t| {:<8}|{}| {}".format("学号", "姓名", "性别", "班级", "电话", "年龄", "出生日期"))
    for vo in alist:
      birth = vo[5]
      bir = birth.strftime("%Y-%m-%d")
      if bir == "1949-10-01":
        bir = "NULL"
      print("{:>5}|\t{:<4}\t| {} |\t{:<10}\t|{:<11}| {} | {}".format(vo[0], vo[1], vo[2], vo[3], vo[4], CalAge(bir), bir))
    db.commit()
  except Exception as err:
    db.rollback()
    print("SQL查看失败!错误:", err)
  db.close()
 
def seeone(a):
  #根据学号,查看某一条数据
  db = pymysql.connect(host="localhost", user="root", password="123456", db="stu", charset="utf8")
  # 创建游标对象
  cursor = db.cursor()
  stuid =int(a)
  sql = "select s.sno,s.name,s.sex,s.cla,s.tel,s.birthday from stu s where s.sno = '%d'" % stuid
  try:
    m = cursor.execute(sql)
    b = cursor.fetchone()
    if b == None:
      print("您的输入有误,将会退出系统")
      quit()
    else:
      print("{:>3}|\t{:<4}\t|{}|\t{:<3}\t\t| {:<8}|{}| {}".format("学号", "姓名", "性别", "班级", "电话", "年龄", "出生日期"))
      birth = b[5]
      bir = birth.strftime("%Y-%m-%d")
      if bir == "1949-10-01":
        bir = "NULL"
      print("{:>5}|\t{:<4}\t| {} |\t{:<10}\t|{:<11}| {:<2} | {}".format(b[0], b[1], b[2], b[3], b[4], CalAge(bir), bir))
    db.commit()
  except Exception as err:
    db.rollback()
    print("SQL查询失败!错误:", err)
  db.close()
 
def addmql():
  #添加一条数据
  db = pymysql.connect(host="localhost", user="root", password="123456", db="stu", charset="utf8")
  # 创建游标对象
  cursor = db.cursor()
  sql = "select s.sno from stu s"
  cursor.execute(sql)
  alist = cursor.fetchall()    #此处读取数据库中的所有学号
  blist = ()           #建立一个空的元组用于存放学号
  print("以下学号已被占用,不可使用:")
  for i in alist:
    blist += i         #存放所有的学号
    print(i[0], end=" ")    #输出已经被使用过的学号
  print()
  sno = int(input("请输入添加的学员的学号:\n"))
  if sno in blist:        #判断学号是否被使用过,学号不可以重复
    print("您输入的学号已被占用!系统即将退出!")
    quit()
  sname = input("请输入添加的学员的姓名:\n")
  sex = input("请输入添加的学员的性别(男or女):\n")
  if sex == "男" or sex == "女":
    sex = sex
  else:
    sex = "男"
    print("性别输入有误,已默认为男")
  cla = input("请输入添加的学员的班级(例:Python01):\n")
  tel = input("请输入添加的学员的电话:\n")
  if tel == re.search(r"(1[3456789]\d{9})", tel):
    tel = tel
    print("电话输入错误,已重置为空")
  else:
    tel = ""
  sbir = input("请输入添加的学员的出生日期(例:2001-1-1):\n")
  if sbir == re.search(r"(\d{4}-\d{1,2}-\d{1,2})", sbir):
    sbir = sbir
  else:
    sbir = "1949-10-01"
    print("出生日期输入错误,已重置为初始值")
  sql = "Insert into stu(sno,name,sex,cla,tel,birthday) values('%d', '%s', '%s', '%s', '%s', '%s')"%(sno, sname, sex, cla, tel, sbir)
  try:
    m = cursor.execute(sql)
    # 事务提交
    db.commit()
    print("成功添加条数:", m)
    print("您添加的信息为:")
    seeone(sno)
  except Exception as err:
    db.rollback()
    print("SQL添加失败!错误:", err)
  db.close()
 
def updatasql():
  #更新修改某条数据
  db = pymysql.connect(host="localhost", user="root", password="123456", db="stu", charset="utf8")
  # 创建游标对象
  cursor = db.cursor()
  stuid = int(input("请输入要修改的学员的学号:\n"))    # 一个班不超过100人,以stuid作为索引
  try:
    seeone(stuid)
    print("======可修改的学员信息的名称======")
    print("{0:2}{1:5}{2:5}{3:5}".format(" ", "1.姓名", "2.性别", "3.班级"))
    print("{0:2}{1:5}{2}".format(" ", "4.电话", "5.出生日期"))
    a = int(input("请选择要修改的学员信息的名称(学号不可修改):\n"))
    if a == 1:
      xm = input("请输入修改后的姓名:\n")
      sql = "UPDATE stu s SET s.name = '%s' WHERE s.sno = '%d'" % (xm, stuid)
    elif a == 2:
      xb = input("请输入修改后的性别(男or女):\n")
      if xb == "男" or xb == "女":
        xb = xb
      else:
        xb = "男"
        print("性别输入有误,已默认为男")
      sql = "UPDATE stu s SET s.sex = '%s' WHERE s.sno = '%d'" % (xb, stuid)
    elif a == 3:
      bj = input("请输入修改后的班级:\n")
      sql = "UPDATE stu s SET s.cla = '%s' WHERE s.sno = '%d'" % (bj, stuid)
    elif a == 4:
      dh = input("请输入修改后的电话:\n")
      sql = "UPDATE stu s SET s.tel = '%s' WHERE s.sno = '%d'" % (dh, stuid)
      if dh == re.search(r"(1[3456789]\d{9})", dh):
        '''正则表达式匹配判断输入是否合格'''
        dh = dh
      else:
        dh = ""
        print("电话输入错误,已重置为空")
    elif a == 5:
      birday = input("请输入修改后的出生日期(格式:2000-1-1):")
      if birday == re.search(r"(\d{4}-\d{1,2}-\d{1,2})", birday):
        '''正则表达式匹配判断输入是否合格'''
        birday = birday
      else:
        birday = "1949-10-01"
        print("出生日期输入错误,已重置为初始值")
      sql = "UPDATE stu s SET s.birthday = '%s' WHERE s.sno = '%d'" % (birday, stuid)
    else:
      print("您的输入有误,将会退出!") # 此处退出防止某些误操作导致的数据库数据泄露
      quit()
    cursor.execute(sql)
    db.commit()
    print("修改后的该学员信息为:")
    seeone(stuid)
  except Exception as err:
    db.rollback()
    print("SQL修改失败!错误:", err)
  db.close()
 
def delsql():
  #删除某条学生数据
  db = pymysql.connect(host="localhost", user="root", password="123456", db="stu", charset="utf8")
  # 创建游标对象
  cursor = db.cursor()
  stuid = int(input("请输入要删除的学员的学号:\n")) # 一个班不超过100人,以stuid作为索引
  try:
    print("======即将删除的学员信息的名称======")
    seeone(stuid)
    a = input("请确认是否删除该学员信息(y/n):\n")
    if a == 'y' or a == 'Y':
      sql = "delete from stu where sno = '%d'"%(stuid)
      cursor.execute(sql)
    else:
      print("取消学员信息删除,即将退出系统")
      quit()
    db.commit()
    print("该学员信息已删除")
  except Exception as err:
    db.rollback()
    print("SQL删除失败!错误:", err)
  db.close()
 
def mainstu():
  while True:
    # 输出初始界面
    print("=" * 12, "学员信息管理系统", "=" * 15)
    print("{0:2}{1:13}{2:15}".format(" ", "1.查看学员信息", "2.添加学员信息"))
    print("{0:2}{1:13}{2:15}".format(" ", "3.修改学员信息", "4.删除学员信息"))
    print("{0:2}{1:13}".format(" ", "5.退出系统"))
    print("=" * 45)
    key = int(input("请输入对应的选择:\n"))
    # 根据键盘值判断并进行操作
    if key == 1:
      print("=" * 12, "学员信息浏览", "=" * 15)
      seesql()
      input("按回车继续")
    elif key == 2:
      print("=" * 12, "学员信息添加", "=" * 15)
      addmql()
      input("按回车继续")
    elif key == 3:
      print("=" * 12, "学员信息修改", "=" * 15)
      seesql()
      updatasql()
      input("按回车继续")
    elif key == 4:
      print("=" * 12, "学员信息删除", "=" * 15)
      seesql()
      delsql()
      input("按回车继续")
    elif key == 5:
      print("=" * 12, "再见", "=" * 12)
      quit()
    else:
      print("=" * 12, "您的输入有误,请重新输入", "=" * 12)
 
mainstu()

配套的数据库文件,内含数据

-- MySQL dump 10.13 Distrib 5.7.12, for Win64 (x86_64)
--
-- Host: localhost  Database: stu
-- ------------------------------------------------------
-- Server version 5.7.17-log
 
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 
--
-- Table structure for table `stu`
--
 
DROP TABLE IF EXISTS `stu`;
/*!40101 SET @saved_cs_client   = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stu` (
 `id` int(3) NOT NULL AUTO_INCREMENT,
 `sno` int(3) NOT NULL,
 `name` varchar(20) NOT NULL,
 `sex` varchar(1) NOT NULL,
 `cla` varchar(10) NOT NULL,
 `tel` varchar(11) DEFAULT NULL,
 `birthday` datetime DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `stu_no_UNIQUE` (`sno`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
 
--
-- Dumping data for table `stu`
--
 
LOCK TABLES `stu` WRITE;
/*!40000 ALTER TABLE `stu` DISABLE KEYS */;
INSERT INTO `stu` VALUES (1,1,'张三','男','Python01','12345678910','1999-01-01 00:00:00'),(2,2,'李四','男','Python01','18866668888','1996-12-06 00:00:00'),(3,3,'王五','男','Python02','12345665410','1996-11-27 00:00:00'),(4,4,'赵六','女','Python02','12332233210','1997-10-24 00:00:00'),(5,5,'qq01','女','Python03','13322223322','1990-01-31 00:00:00'),(6,6,'qq02','男','Python03','12288886666','1992-02-20 00:00:00'),(7,7,'qq03','女','Python03','13579264801','2000-10-30 00:00:00'),(8,8,'uu01','男','Python01','18898084886','1998-08-08 00:00:00'),(9,9,'uu02','女','Python02','12022000022','1994-04-01 00:00:00'),(10,10,'aa','女','Python02','18899998888','2004-04-04 00:00:00'),(11,11,'bb','男','Python03','19264664234','1995-05-15 00:00:00'),(25,12,'uu10','男','Python04','17788992332','1996-12-06 00:00:00'),(28,13,'uu10','女','Python04','13571854999','1996-12-06 00:00:00');
/*!40000 ALTER TABLE `stu` ENABLE KEYS */;
UNLOCK TABLES;
 
--
-- Dumping events for database 'stu'
--
 
--
-- Dumping routines for database 'stu'
--
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
 
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
 

-- Dump completed on 2018-03-31 15:10:58

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 提取文件的小程序
Jul 29 Python
从零学python系列之新版本导入httplib模块报ImportError解决方案
May 23 Python
python多线程用法实例详解
Jan 15 Python
浅析Python中yield关键词的作用与用法
Nov 29 Python
Python实现二维数组按照某行或列排序的方法【numpy lexsort】
Sep 22 Python
解决python3中自定义wsgi函数,make_server函数报错的问题
Nov 21 Python
python 实现对文件夹内的文件排序编号
Apr 12 Python
python ChainMap的使用和说明详解
Jun 11 Python
python通过robert、sobel、Laplace算子实现图像边缘提取详解
Aug 21 Python
如何用PyPy让你的Python代码运行得更快
Dec 02 Python
python中Array和DataFrame相互转换的实例讲解
Feb 03 Python
Python中使用Lambda函数的5种用法
Apr 01 Python
python 使用sys.stdin和fileinput读入标准输入的方法
Oct 17 #Python
Python实现Dijkstra算法
Oct 17 #Python
使用Python抓取豆瓣影评数据的方法
Oct 17 #Python
python 对key为时间的dict排序方法
Oct 17 #Python
解决python中os.listdir()函数读取文件夹下文件的乱序和排序问题
Oct 17 #Python
通过python将大量文件按修改时间分类的方法
Oct 17 #Python
python检测文件夹变化,并拷贝有更新的文件到对应目录的方法
Oct 17 #Python
You might like
php 文件上传实例代码
2012/04/19 PHP
php防止sql注入示例分析和几种常见攻击正则表达式
2014/01/12 PHP
PHP实现的简单对称加密与解密方法实例小结
2017/08/28 PHP
基于Laravel 多个中间件的执行顺序详解
2019/10/21 PHP
TP5框架model常见操作示例小结【增删改查、聚合、时间戳、软删除等】
2020/04/05 PHP
使用jscript实现二进制读写脚本代码
2008/06/09 Javascript
javascript 获取所有id中包含某关键字的控件的实现代码
2010/11/25 Javascript
Java 正则表达式学习总结和一些小例子
2012/09/13 Javascript
Javascript 鼠标移动上去 滑块跟随效果代码分享
2013/11/23 Javascript
分享两个手机访问pc网站自动跳转手机端网站代码
2020/12/24 Javascript
Javascript获取表单名称(name)的方法
2015/04/02 Javascript
Javascript仿新浪游戏频道鼠标悬停显示子菜单效果
2015/08/21 Javascript
深入学习jQuery Validate表单验证(二)
2016/01/18 Javascript
Angularjs中使用Filters详解
2016/03/11 Javascript
javaScript给元素添加多个class的简单实现
2016/07/20 Javascript
Angular.js之作用域scope'@','=','&amp;'实例详解
2017/02/28 Javascript
使用axios实现上传图片进度条功能
2017/12/21 Javascript
javascript trie前缀树的示例
2018/01/29 Javascript
vue自定义正在加载动画的例子
2019/11/14 Javascript
[02:47]2018年度DOTA2最佳辅助位选手4号位-完美盛典
2018/12/17 DOTA
[01:54]TI珍贵瞬间系列(三):翻盘
2020/08/28 DOTA
Python中使用异常处理来判断运行的操作系统平台方法
2015/01/22 Python
python通过wxPython打开一个音频文件并播放的方法
2015/03/25 Python
在Mac OS上搭建Python的开发环境
2015/12/24 Python
Python编程scoketServer实现多线程同步实例代码
2018/01/29 Python
TensorFlow实现Softmax回归模型
2018/03/09 Python
python3中zip()函数使用详解
2018/06/29 Python
Python基于sklearn库的分类算法简单应用示例
2018/07/09 Python
用Python 爬取猫眼电影数据分析《无名之辈》
2020/07/24 Python
CSS3属性box-sizing使用指南
2014/12/09 HTML / CSS
求职信模板怎么做
2014/01/26 职场文书
冬季施工防火方案
2014/05/17 职场文书
鲁滨孙漂流记读书笔记
2015/06/30 职场文书
Python爬虫之自动爬取某车之家各车销售数据
2021/06/02 Python
详细谈谈MYSQL中的COLLATE是什么
2021/06/11 MySQL
MySQL的意向共享锁、意向排它锁和死锁
2022/07/15 MySQL