Examples of Python operations on MySQL database

Source: Internet
Author: User
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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.