Home > Article > Backend Development > Detailed explanation of examples of python operations on Mysql database
import MySQLdb#引入mysql模块 class ManagerDB:#创建一个类 def __init__(self): self.db=None self.cursor=None self.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('请输入要选择的编号:') if xz==1: self.student = self.addStudent() if xz==2: self.showStudent() if xz==3: self.delStudent() if xz==4: print '再见' self.db.close() self.cursor.close() break def addStudent(self):#添加 sname=raw_input('请输入要添加学生的姓名') ssex=raw_input('请输入要添加学生的性别') sage=raw_input('请输入要添加学生的年龄') try: sq1="insert into student(name,sex,age)values('%s','%s','%s')"%(sname,ssex,sage) for i in range(10): self.cursor.execute(sq1) self.db.commit() print '成功添加10条信息' except: print '添加失败' self.db.rollback() def showStudent(self):#查看 self.cursor.execute('select * from student') print 'id 姓名 性别 年龄' for i in self.cursor: print i[0],i[1],i[2],i[3] def delStudent(self):#删除 try: self.cursor.execute('delete from student where id=5') self.db.commit() print '成功删除id为5的信息' except: print '删除失败' self.db.rollback() def menu(self): print ''' ---------------------------- 1 添加信息 2 显示数据 3 删除数据 4 退出系统 ---------------------------- ''' if __name__ == '__main__': s=ManagerDB()#实例化对象 s.start()
The above is the detailed content of Detailed explanation of examples of python operations on Mysql database. For more information, please follow other related articles on the PHP Chinese website!