• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python对Mysql数据库进行操作的实例详解

python 搞代码 4年前 (2022-01-09) 14次浏览 已收录 0个评论
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()

以上就是python对Mysql数据库进行操作的实例详解的详细内容,更多请关注搞代码gaodaima其它本文来源gaodai$ma#com搞$$代**码网相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python对Mysql数据库进行操作的实例详解
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址