基於python的學生管理系統(含數據庫版本)


這次支持連接到后台的數據庫,直接和數據庫進行交互,實現基本的增刪查改

  1 #!/usr/bin/python3
  2 # coding=utf-8
  3 """
  4 ***********************help document****************************************
  5 Usage:
  6     this is a simple student grades system,now is simple
  7     when start the programming,you can do following operations
  8     enter 'a' is to insert data into database
  9     enter 'b' is to display all data in database
 10     enter 'c' is to query the specify info in database
 11     enter 'h' is to see this help dacument
 12     enter 'd' is to delete someone student's info
 13     enter nothing is to do nothing,you can enter again
 14     simple help document is: "a--insert/b--display/c--query/h--help/d--delete/''--default"
 15 Example:
 16     please enter the OPcode: a  then [enter]
 17 *****************************************************************************
 18 
 19 """
 20 
 21 #引入pymysql這個庫用來連接數據據
 22 import pymysql
 23 
 24 #打印幫助文檔
 25 def help_document():
 26     print(__doc__)
 27 
 28 #在已有的數據庫上創建數據庫的表
 29 def create_database():
 30     #在mysql中創建數據庫student_db
 31     db = pymysql.connect('localhost', 'root', 'root')
 32     name = 'student_db'
 33     cursor = db.cursor()
 34     cursor.execute('drop database if exists ' + name)
 35     cursor.execute('create database if not exists ' + name)
 36     db.close()
 37     #在數據庫student_db中創建數據表student_table
 38     db = pymysql.connect('localhost', 'root', 'root', 'student_db')
 39     cursor = db.cursor()
 40     name = 'student_table'
 41     cursor.execute('drop table if exists ' + name)
 42     sql = """create table student_table(
 43     name varchar(30) primary key not null,
 44     age  varchar(10),
 45     id   varchar(20),
 46     grade  varchar(10))"""
 47     cursor.execute(sql)
 48     db.commit()
 49     db.close()
 50 
 51 #數據庫的插入
 52 def insert_db(name,age,id,grade):
 53     db = pymysql.connect('localhost', 'root', 'root','student_db')
 54     cursor = db.cursor()
 55     sql = "insert into student_table (name,age,id,grade) values ('%s','%s','%s','%s')" % \
 56           (name,age,id,grade)
 57     cursor.execute(sql)
 58     db.commit()
 59     db.close()
 60 
 61 #打印數據庫中所有數據
 62 def display_db():
 63     db = pymysql.connect('localhost', 'root', 'root', 'student_db')
 64     cursor = db.cursor()
 65     sql = "select * from student_table"
 66     try:
 67         cursor.execute(sql)
 68         result = cursor.fetchall()
 69         for row in result:
 70             name = row[0]
 71             age = row[1]
 72             id = row[2]
 73             grade = row[3]
 74             print("name: '%s',age: '%s',id: '%s',grade: '%s'" % (name,age,id,grade))
 75         print("that's all diaplayed!")
 76     except:
 77         print('nothing has been displayed...')
 78     db.close()
 79 
 80 #數據庫的查找
 81 def query_db(name):
 82     db = pymysql.connect('localhost', 'root', 'root', 'student_db')
 83     cursor = db.cursor()
 84     sql = "select * from student_table where name = '%s' " % name
 85     try:
 86         cursor.execute(sql)
 87         result = cursor.fetchall()
 88         for row in result:
 89             name1 = row[0]
 90             age1 = row[1]
 91             id1 = row[2]
 92             grade1 = row[3]
 93         print("name: '%s',age: '%s',id: '%s',grade: '%s'" % \
 94               (name1,age1,id1,grade1))
 95         print('the query is over!')
 96     except:
 97         print('can not query data!')
 98     db.close()
 99 
100 #更新數據庫
101 def update_db(name,age,id,grade):
102     db = pymysql.connect('localhost', 'root', 'root', 'student_db')
103     cursor = db.cursor()
104     sql = "update student_table set age = '%s',id = '%s',grade = '%s' where name = '%s'" % \
105           (age,id,grade,name)
106     try:
107         cursor.execute(sql)
108         db.commit()
109         print('updated successfully!')
110     except:
111         print('can not update data!')
112     db.close()
113 
114 
115 #數據庫的刪除
116 def delete_db(name):
117     db = pymysql.connect('localhost', 'root', 'root', 'student_db')
118     cursor = db.cursor()
119     sql = "delete from student_table where name = '%s'" % name
120     try:
121         cursor.execute(sql)
122         db.commit()
123         print('delete the student info successfully!')
124     except:
125         print('delete failed...')
126     db.close()
127 
128 # 實現switch-case語句
129 class switch(object):
130     def __init__(self, value):
131         self.value = value
132         self.fall = False
133 
134     def __iter__(self):
135         """Return the match method once, then stop"""
136         yield self.match
137         raise StopIteration
138 
139     def match(self, *args):
140         """Indicate whether or not to enter a case suite"""
141         if self.fall or not args:
142             return True
143         elif self.value in args:  # changed for v1.5, see below
144             self.fall = True
145             return True
146         else:
147             return False
148 
149 #建立一個學生類
150 class student:
151     #構造函數
152     def __init__(self, name, age, id, grade):
153         self.next = None
154         self.name = name
155         self.age = age
156         self.id = id
157         self.grade = grade
158     #每個學生可以輸出自己的信息
159     def show(self):
160         print('name:', self.name, ' ', 'age:', self.age, ' ', 'id:', self.id, ' ', 'grade:', self.grade)
161 
162 #建立一個學生列表類
163 class stulist:
164     #構造函數
165     def __init__(self):
166         self.head = student('', 0, 0, 0)
167     #輸出數據庫中所有的數據
168     def display(self):
169         display_db()
170     #新增學生數據
171     def insert(self):
172         print('please enter:')
173         name = input('name:')
174         age = input('age:')
175         id = input('id:')
176         grade = input('grade:')
177         insert_db(name, age, id, grade)
178 
179     #查詢學生數據
180     def query(self):
181         name = input('please enter the name you want to query:')
182         query_db(name)
183 
184     #刪除學生數據
185     def delete(self):
186         name = input("please enter the student'name you want to delete:")
187         delete_db(name)
188 
189 #主函數,程序的入口
190 def main():
191     stulist1 = stulist()
192     user_input = input('please enter the OPcode:')
193     while user_input:
194         print("a--insert/b--display/c--query/h--help/d--delete/''--default")
195         for case in switch(user_input):
196             if case('a'): #按下'a'鍵
197                 stulist1.insert()
198                 user_input = input('please enter the OPcode:')
199                 break
200             if case('b'):  #按下'b'鍵
201                 stulist1.display()
202                 user_input = input('please enter the OPcode:')
203                 break
204             if case('c'):  #按下'c'鍵
205                 stulist1.query()
206                 user_input = input('please enter the OPcode:')
207                 break
208             if case('d'):  #按下'd'鍵
209                 stulist1.delete()
210                 user_input = input('please enter your OPcode:')
211                 break
212             if case('h'):  #按下'h'鍵
213                 help_document()
214                 user_input = input('please enter your OPcode:')
215                 break
216             if case():  # default
217                 print('please enter the OPcode...')
218                 user_input = input('please enter the OPcode:')
219                 break
220 
221 
222 if __name__ == "__main__":
223     #第一次運行程序需要建立新的數據庫,需要運行下面注釋的一行代碼,下次運行得將其注釋掉
224     #create_database()
225     main()

結果效果圖:

輸入'h'查看幫助文檔

輸入'b'來查詢數據庫數據:

 

這個版本還是很粗糙,訪問速度也很慢,如果以后還有時間的話,我會做一個界面出來,改進下和數據庫的交互方式。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM