データベース版の学生管理システム

13831 ワード

import MySQLdb #  MySQL  

class Student: # student
def __init__(self):
self.db = None
self.cursor = None
self.connect() #

def connect(self):
self.db = MySQLdb.connect(host = 'localhost',user = 'root',passwd = '123456',db = 'student_1')
self.cursor = self.db.cursor()

def start(self):#
while True:
self.menu1()
num = raw_input(' :')
print num.isdigit()
if num.isdigit() == False:
continue
num = int(num)
if num == 1:
self.showStudent()
elif num == 2:
self.addStudent()
elif num == 3:
self.delStudent()
elif num == 4:
self.updateStudent()
elif num == 5:
print ' '
self.close()
break

def showStudent(self):#
while True:
self.menu2()
num = input(' :(0—3)')
if num == 1:
print 'ID '
self.cursor.execute('select * from student')
for i in self.cursor.fetchall():
print i[0],i[1],i[2],i[3]
elif num == 2:
sid = input(' ID:')
self.cursor.execute('select * from student where id = %d'%sid)
if self.cursor.rowcount == 0:
print ' '
else:
print 'ID '
for i in self.cursor:
print i[0],i[1],i[2],i[3]
elif num == 3:
sname = raw_input(' :')
self.cursor.execute("select * from student where name = '%s'"%sname)
if self.cursor.rowcount == 0:
print ' '
else:
print 'ID '
for i in self.cursor.fetchall():
print i[0],i[1],i[2],i[3]
else:
self.start()
break

def addStudent(self):#
while True:
sname = raw_input(' :')
sage = raw_input(' :')
ssax = raw_input(' :')
try:
sql = 'insert into student(name,age,sax) values(%s,%s,%s)'
self.cursor.execute(sql,(sname,sage,ssax))
self.db.commit()
print ' '
except:
self.db.rollback()
print ' '
q = raw_input(' ,Q ').lower()
if q == 'q':
break

def delStudent(self):#
self.menu3()
num = input(' :')
if num == 1:
sid = raw_input(' ID ID:')
list1 = sid.split(' ')
print list1
list2 = map(lambda x:(int(x),),list1)
print list2
sql ='delete from student where id =%s'
try:
self.cursor.executemany(sql,list2)
self.db.commit()
print ' '
except:
print ' '
self.db.rollback()
elif num == 2:
sname = raw_input(' :')
try:
self.cursor.execute("delete from student where name ='%s'"%sname)
self.db.commit()
print ' !'
except:
print ' !'
self.db.rollback()
else:
pass

def updateStudent(self):#
sid = input(' ID:')
sname = raw_input(' :')
sage = raw_input(' :')
ssax = raw_input(' :')
try:
self.cursor.execute("update student set name='%s',age=%s,sax='%s' where id = %s"%(sname,sage,ssax,sid))
self.db.commit()
print ' !'
except:
print ' !'
self.db.rollback()

def menu1(self):
print """
--------------- ---------------
1
2
3
4
5
------------------------------------------
"""

def menu2(self):
print """
---------- ----------
0
1
2 ID
3
----------------------------
"""
def menu3(self):
print """
---------- ----------
0
1 ID
2
"""

def close(self):
self.db.close()

if __name__ == '__main__':
student =Student()
student.start()

転載先:https://www.cnblogs.com/a1440355978/p/7079320.html