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

 更新时间:2018年01月15日 10:34:17   作者:坏蛋是我  
这篇文章主要介绍了Python操作mysql数据库实现增删查改功能的方法,涉及Python针对mysql数据库的连接、增删改查等相关操作技巧,需要的朋友可以参考下

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

#coding=utf-8
import MySQLdb
class 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使用requests及BeautifulSoup构建爬虫实例代码

    Python使用requests及BeautifulSoup构建爬虫实例代码

    这篇文章主要介绍了Python使用requests及BeautifulSoup构建爬虫,介绍了具体操作步骤和实例代码等相关内容,小编觉得还是挺不错的,这里分享给大家,需要的朋友可以参考下
    2018-01-01
  • 基于Python实现口罩佩戴检测功能

    基于Python实现口罩佩戴检测功能

    这篇文章主要介绍了基于Python实现的口罩佩戴检测,在本次实验中,我们要建立一个目标检测的模型,可以识别图中的人是否佩戴了口罩,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2022-05-05
  • Python读取pdf、word、excel、ppt、csv和txt文件提取所有文本

    Python读取pdf、word、excel、ppt、csv和txt文件提取所有文本

    这篇文章主要给大家介绍了关于Python读取pdf、word、excel、ppt、csv和txt文件提取所有文本的相关资料,文中通过代码示例将实现的方法介绍的非常详细,需要的朋友可以参考下
    2023-08-08
  • Python教程之Python多态的深层次理解

    Python教程之Python多态的深层次理解

    相信很多在学Python的朋友都有了解过多态,本篇文章来带大家更进一步的深入了解Python多态,有需要的朋可以借鉴参考下,希望可以有所帮助
    2021-09-09
  • 关于 Python opencv 使用中的 ValueError: too many values to unpack

    关于 Python opencv 使用中的 ValueError: too many values to unpack

    这篇文章主要介绍了关于 Python opencv 使用中的 ValueError: too many values to unpack,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-06-06
  • python删除本地夹里重复文件的方法

    python删除本地夹里重复文件的方法

    这篇文章主要为大家详细介绍了python删除本地夹里重复文件的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-05-05
  • python实现的重启关机程序实例

    python实现的重启关机程序实例

    这篇文章主要介绍了python实现的重启关机程序,有不错的借鉴价值,需要的朋友可以参考下
    2014-08-08
  • PyQt中使用QtSql连接MySql数据库的方法

    PyQt中使用QtSql连接MySql数据库的方法

    这篇文章主要介绍了PyQt中使用QtSql连接MySql数据库的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • python获取指定目录下所有文件名列表的方法

    python获取指定目录下所有文件名列表的方法

    这篇文章主要介绍了python获取指定目录下所有文件名列表的方法,涉及Python目录及文件操作的相关技巧,需要的朋友可以参考下
    2015-05-05
  • python学生管理系统

    python学生管理系统

    这篇文章主要为大家详细介绍了python学生管理系统的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01

最新评论