学生管理系统(面向对象版)
学生管理系统是我们作为初学各类语言是都会写的,在此小柒提供一个用类封装的,连接Sqlite数据库的。代码如下:
import sqlite3
class StudentManager(object):
def __init__(self):
"""初始化"""
self.conn = None
self.cursor = None
def create_table(self):
"""创建表"""
self.connect_sql()
sql = """ CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY ,name VARCHAR NOT NULL , sex VARCHAR ,age INTEGER ,phone VARCHAR ) """
self.cursor.execute(sql)
self.close_sql()
def connect_sql(self):
"""连接数据库"""
self.conn = sqlite3.connect('testsqlite.db')
self.cursor = self.conn.cursor()
def close_sql(self):
"""关闭数据库"""
self.conn.commit()
self.cursor.close()
self.conn.close()
def insert(self):
"""添加数据函数"""
self.connect_sql()
while True:
name = input('请输入要添加学员姓名: ')
sex = input('请输入要添加学员性别: ')
age = input('请输入要添加学员年龄: ')
phone = input('请输入要添加学员电话: ')
self.cursor.execute(""" INSERT INTO students (name, sex, age, phone) VALUES ('{}', '{}', {}, '{}')""".format(name, sex, age, phone))
is_next = input('回车继续添加,退出请按q')
print('添加成功!')
if is_next == 'q':
break
self.close_sql()
def delete(self):
"""删除学生信息函数"""
self.select()
self.connect_sql()
print('a.按id删除')
print('b.删除所有')
select = input('请问您想选择哪种删除方式?')
while True:
if select == 'a':
s_id = input('请输入您要删除的学生的id:')
self.cursor.execute(""" DELETE FROM students WHERE id={}""".format(s_id))
is_next = input('继续请回车,退出请按q')
print('删除成功!')
if is_next == 'q':
break
else:
is_sure = input('确定要全部删除吗')
self.cursor.execute(""" DROP TABLE students """)
break
return
self.close_sql()
def select(self):
"""查询学生信息函数"""
print('行号\t\t姓名\t\t性别\t\t年龄\t\t电话')
print('-'*50)
self.connect_sql()
self.cursor.execute(""" SELECT * FROM students """)
stu_list = self.cursor.fetchall()
for idx, stu in enumerate (stu_list):
print('{}\t\t{}\t\t{}\t\t{}\t\t{}'.format(idx+1, stu[1], stu[2], stu[3], stu[4]))
self.close_sql()
def modify(self):
"""修改学生信息函数"""
self.select()
self.connect_sql()
while True:
s_id = input('请输入要修改的学员id:')
name = input('请输入要修改学员姓名: ')
sex = input('请输入要修改学员性别: ')
age = input('请输入要修改学员年龄: ')
phone = input('请输入要修改学员电话: ')
self.cursor.execute(""" UPDATE students SET name="{}", sex="{}", age={}, phone="{}" WHERE id={}""".format(name, sex, age, phone, s_id))
is_next = input('回车继续修改,退出请按q')
print('修改成功!')
if is_next == 'q':
break
self.close_sql()
def show_option(self):
"""展示选项列表"""
print('*' * 45)
print('***** 1.查询学员信息 *****')
print('***** 2.添加学员信息 *****')
print('***** 3.修改学员信息 *****')
print('***** 4.删除学员信息 *****')
print('***** 0.退出程序 *****')
def run(self):
"""程序运行的主要函数"""
self.create_table()
while True:
self.show_option()
try:
select = int(input('请选择您要进行的操作:'))
if select == 1:
self.select()
elif select == 2:
self.insert()
elif select == 3:
self.modify()
elif select == 4:
self.delete()
else:
print('再见~~~')
break
except Exception as e:
print('您输入的选项不对,请重新输入:')
if __name__ == '__main__':
sm = StudentManager()
sm.run()
如有雷同,纯属意外,O(∩_∩)O哈哈~