侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python操作mysql数据库实现增删查改功能的方法

Python  /  管理员 发布于 7年前   414

本文实例讲述了Python操作mysql数据库实现增删查改功能的方法。分享给大家供大家参考,具体如下:

#coding=utf-8import MySQLdbclass Mysql_Oper:  def __init__(self,host,user,passwd,db):    self.host=host    self.user=user    self.passwd=passwd    self.database=db  def db_connecet(self):    try:      #连接      conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.database,charset="utf8")      cursor = conn.cursor()    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def drop_table(self,table):    try:      #删除表      sql = "drop table if exists" + table      cursor.execute(sql)    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def create_table(self,table):    try:      if table=="dept":        #创建        sql = "create table if not exists dept(deptno int primary key, dname varchar(50),loc varchar(50))"        cursor.execute(sql)      elif table=="emp":        sql == "create table if not exists emp(empno INT PRIMARY KEY,ename VARCHAR(50),job VARCHAR(50),mgr INT,hiredate DATE,sal DECIMAL(7,2),COMM DECIMAL(7,2),deptno INT,loc varchar(50),CONSTRAINT fk_emp FOREIGN KEY(mgr) REFERENCES emp(empno))"        cursor.execute(sql)      elif table=="salgrade":        sql = "create table if not exists salgrade(grade INT PRIMARY KEY,losal INT,hisal INT)"        cursor.execute(sql)      elif table=="stu":        #创建        sql = "create table if not exists dept(sid INT PRIMARY KEY,sname VARCHAR(50),age INT,gander VARCHAR(10),province VARCHAR(50),tuition INT)"        cursor.execute(sql)      else:        print u"输入错误的表名,表明为dept、emp、salgrade、stu..."    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def inser_onedata_table(self,table):    try:      if table=="dept":        sql = "insert into dept values(%s,%s,%s)"        param = (40, 'cai wu bu', 'wu han')        n = cursor.execute(sql,param)        print 'insert',n      elif table=="emp":        sql = "insert into emp values(%s,%s,%s,%s,%s,%s,%s,%s)"        param = (1009, 'a niu', 'dong shi zhang', NULL, '2001-11-17', 50000, NULL, 10)        n = cursor.execute(sql,param)        print 'insert',n      elif table=="salgrade":        sql = "insert into salgrade values(%s,%s,%s)"        param = (1, 7000, 12000)        n = cursor.execute(sql,param)        print 'insert',n      elif table=="stu":        sql = "insert into stu values(%s,%s,%s,%s,%s,%s)"        param = ('1', '001', '23', 'nan', 'bei jing', '1500')        n = cursor.execute(sql,param)        print 'insert',n      else:        print u"输入错误的表名,表明为dept、emp、salgrade、stu..."    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def inser_muldata_table(self,table):    try:      if table=="dept":        sql = "insert into dept values(%s,%s,%s)"        param = ((10, 'jiao yan bu', 'bei jing'),(20, 'xue gong bu', 'shang hai'),(30, 'xiao shou bu', 'guang zhou'))        n = cursor.executemany(sql,param)        print 'insert',n      elif table=="emp":        sql = "insert into emp values(%s,%s,%s,%s,%s,%s,%s,%s)"        param = ((1004, 'liu bei', 'jing li', 1009, '2001-04-02', 29750, NULL, 20), (1006, 'guan yu', 'jing li', 1009, '2001-05-01', 28500, NULL, 30), (1008, 'zhu ge liang', 'fen xi shi', 1004, '2007-04-19', 30000, NULL, 20), (1013, 'pang', 'fen xi shi', 1004, '2001-12-03', 30000, NULL, 20), (1002, 'dai', 'xiao shou yuan', 1006, '2001-02-20', 16000, 3000, 30), (1003, 'tian zheng', 'xiao shou yuan', 1006, '2001-02-22', 12500, 5000, 30), (1005, 'xie xun', 'xiao shou yuan', 1006, '2001-09-28', 12500, 14000, 30), (1010, 'wei yi xiao', 'xiao shou yuan', 1006, '2001-09-08', 15000, 0, 30) )        n = cursor.executemany(sql,param)        print 'insert',n      elif table=="salgrade":        sql = "insert into salgrade values(%s,%s,%s)"        param = ((2, 12010, 14000),(3, 14010, 20000),(4, 20010, 30000),(5, 30010, 99990))        n = cursor.executemany(sql,param)        print 'insert',n      elif table=="stu":        sql = "insert into stu values(%s,%s,%s,%s,%s,%s)"        param = ( ('2', '002', '25', 'nan', 'liao ning', '2500'),   ('3', '003', '22', 'nan', 'bei jing', '3500'),   ('4', '004', '25', 'nan', 'bei jing', '1500'),   ('5', '005', '23', 'nv', 'bei jing', '1000'),   ('6', '006', '22', 'nv', 'shan dong', '2500'),   ('7', '007', '21', 'nv', 'bei jing', '1600'),   ('8', '008', '23', 'nan', 'bei jing', '3500'),   ('9', '009', '23', 'nv', 'guang zhou', '2500'),   ('10', '010', '18', 'nan', 'shan xi', '3500'),   ('11', '011', '23', 'nan', 'hu bei', '4500'),   ('12', '011', '24', 'nan', 'bei jing', '1500'),   ('13', '011', '24', 'nan', 'liao ning', '2500'),   ('14', '011', '22', 'nan', 'bei jing', '3500'),   ('15', '011', '25', 'nan', 'bei jing', '1500'),   ('16', '011', '23', 'nv', 'bei jing', '1000'),   ('17', '011', '22', 'nv', 'shan dong', '2500'),   ('18', '011', '21', 'nv', 'bei jing', '1600'),   ('19', '011', '23', 'nan', 'bei jing', '3500'),   ('20', '011', '23', 'nv', 'guang zhou', '2500'),   ('21', '011', '18', 'nan', 'shan xi', '3500'),   ('22', '011', '23', 'nan', 'hu bei', '4500'),   ('23', '011', '23', 'nan', 'bei jing', '1500'),   ('24', '011', '25', 'nan', 'liao ning', '2500'),   ('25', '011', '22', 'nan', 'bei jing', '3500'),   ('26', '011', '25', 'nan', 'bei jing', '1500'),   ('27', '011', '23', 'nv', 'bei jing', '1000'),   ('28', '011', '22', 'nv', 'shan dong', '2500'),   ('29', '011', '21', 'nv', 'bei jing', '1600'),   ('30', '011', '23', 'nan', 'bei jing', '3500'),   ('31', '011', '23', 'nv', 'guang zhou', '2500'),   ('32', '011', '18', 'nan', 'shan xi', '3500'),   ('33', '033', '23', 'nan', 'hu bei', '4500'),   ('34', '034', '23', 'nan', 'bei jing', '1500'),   ('35', '035', '25', 'nan', 'liao ning', '2500'),   ('36', '036', '22', 'nan', 'bei jing', '3500'),   ('37', '037', '25', 'nan', 'bei jing', '1500'),   ('38', '038', '23', 'nv', 'bei jing', '1000'),   ('39', '039', '22', 'nv', 'shan dong', '2500'),   ('40', '040', '21', 'nv', 'bei jing', '1600'),   ('41', '041', '23', 'nan', 'bei jing', '3500'),   ('42', '042', '23', 'nv', 'guang zhou', '2500'),   ('43', '043', '18', 'nan', 'shan xi', '3500'),   ('44', '044', '23', 'nan', 'hu bei', '4500'),   ('45', '045', '23', 'nan', 'bei jing', '1500'),   ('46', '046', '25', 'nan', 'liao ning', '2500'),   ('47', '047', '22', 'nan', 'bei jing', '3500'),   ('48', '048', '25', 'nan', 'bei jing', '1500'),   ('49', '049', '23', 'nv', 'bei jing', '1000'),   ('50', '050', '22', 'nv', 'shan dong', '2500'),   ('51', '051', '21', 'nv', 'bei jing', '1600'),   ('52', '052', '23', 'nan', 'bei jing', '3500'),   ('53', '053', '23', 'nv', 'guang zhou', '2500'),   ('54', '054', '18', 'nan', 'shan xi', '3500'),   ('55', '055', '23', 'nan', 'hu bei', '4500'))        n = cursor.executemany(sql,param)        print 'insert',n      else:        print u"输入错误的表名,表明为dept、emp、salgrade、stu..."    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def update_table(self,table,no,upno):    try:      if table=="dept":        #创建        sql = "update dept set deptno=%s where deptno=" +no        param = (upno)        n = cursor.execute(sql,param)        print 'update',n      elif table=="emp":        sql = "update emp set empno=%s where empno=" +no        param = (upno)        n = cursor.execute(sql,param)        print 'update',n      elif table=="salgrade":        sql = "update salgrade set grade=%s where grade=" +no        param = (upno)        n = cursor.execute(sql,param)        print 'update',n      elif table=="stu":        sql = "update stu set sname=%s where sname=" +no        param = (upno)        n = cursor.execute(sql,param)        print 'update',n      else:        print u"输入错误的表名,表明为dept、emp、salgrade、stu..."    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def query_data(self,table):    try:      #查询      sql="select * from "+table      n = cursor.execute(sql)      print cursor.fetchall()      for row in cursor.fetchall():        print row        for r in row:          print r    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  def delete_data(self,table,no)    try:      if table=="dept":        sql = "delete from dept where deptno=%s"        param = (upno)        n = cursor.execute(sql,param)        print 'delete',n      elif table=="emp":        sql = "delete from emp where empno=%s"        param = (upno)        n = cursor.execute(sql,param)        print 'delete',n      elif table=="salgrade":        sql = "delete from salgrade where grade=%s"        param = (upno)        n = cursor.execute(sql,param)        print 'delete',n      elif table=="stu":        sql = "delete from stu where sname=%s "        param = (upno)        n = cursor.execute(sql,param)        print 'delete',n      else:        print u"输入错误的表名,表明为dept、emp、salgrade、stu..."    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])  del down_db(self):    try:      cursor.close()      #提交      conn.commit()      #关闭      conn.close()    except MySQLdb.Error,e:        print "Mysql Error %d: %s" % (e.args[0], e.args[1])mysqlDB=Mysql_Oper("127.0.0.1","root","root","exam")mysqlDB.db_connecet()mysqlDB.drop_table("dept")for table in ["dept","emp","salgrade","stu"]  mysqlDB.create_table(table)  mysqlDB.inser_onedata_table(table)  mysqlDB.inser_muldata_table(table)  mysqlDB.query_data(table)mysqlDB.down_db()

后期我会把数据整合到CSV文件中,操作CSV文件对数据进行操作

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python+MySQL数据库程序设计入门教程》、《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    python+opencv实现动态物体追踪
    下一条:
    python逆向入门教程
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客