Import mysqldb# introduced MySQL module class Managerdb: #创建一个类 def __init__ (self): Self.db=none self.cursor=none S Elf.connit () def connit (self): #链接数据库 self.db=mysqldb.connect (host= ' 127.0.0.1 ', user= ' root ', passwd= ' 123456 ', db= ' Exam_python ') #host主机名 #user用户名 #passwd用户名密码 #db数据库 self.cursor=self.db.cursor () def start (self): #开始 While True:self.menu () #引入菜单栏 xz=input (' Please enter the number to select: ') If xz==1:self.student = Self.addstudent () if xz==2:self.showstudent () if xz==3:self.delstudent () if xz==4: print ' Goodbye ' Self.db.close () Self.cursor.close () Break def addstudent (self): #添加 sname=raw_input ( ' Please enter the name of the student to be added ' ssex=raw_input (' Please enter the gender of the student to be added ') sage=raw_input (' Please enter the age of the student to be added ') try:sq1= "insert into S Tudent (Name,sex,age) VALUES ('%s ', '%s ', '%s ') "% (sname,ssex,sage) for I in range: Self.cursor.execute (sq1) se Lf.db.commit () print ' successfully added 10 message' Except:print ' Add failed ' Self.db.rollback () def showstudent (self): #查看 Self.cursor.execute (' SELECT * from student ') print ' ID name Gender age ' for I in Self.cursor:print i[0],i[1],i[2],i[3]def delstude NT (self): the #删除 try:self.cursor.execute (' Delete from student where id=5 ') self.db.commit () print ' successfully deleted a letter with ID 5 Except:print ' Delete failed ' Self.db.rollback () def menu (self): print '----------- -----------------1 Add information 2 Show data 3 Delete data 4 exit the system--------- -------------------' if __name__ = = ' __main__ ': S=managerdb () #实例化对象 S.start ()