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


Posted in Python onJanuary 15, 2018

本文实例讲述了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 相关文章推荐
用python写asp详细讲解
Dec 16 Python
python基于phantomjs实现导入图片
May 13 Python
Python实现ping指定IP的示例
Jun 04 Python
解决pycharm回车之后不能换行或不能缩进的问题
Jan 16 Python
django2笔记之路由path语法的实现
Jul 17 Python
在django中自定义字段Field详解
Dec 03 Python
python字符串替换re.sub()实例解析
Feb 09 Python
Python使用matplotlib绘制圆形代码实例
May 27 Python
Python新手学习函数默认参数设置
Jun 03 Python
用pandas划分数据集实现训练集和测试集
Jul 20 Python
如何在Anaconda中打开python自带idle
Sep 21 Python
python pyhs2 的安装操作
Apr 07 Python
使用python编写简单的小程序编译成exe跑在win10上
Jan 15 #Python
python逆向入门教程
Jan 15 #Python
Python3一行代码实现图片文字识别的示例
Jan 15 #Python
Python编程二分法实现冒泡算法+快速排序代码示例
Jan 15 #Python
selenium python浏览器多窗口处理代码示例
Jan 15 #Python
100行python代码实现跳一跳辅助程序
Jan 15 #Python
tornado 多进程模式解析
Jan 15 #Python
You might like
PHP获取类中常量,属性,及方法列表的方法
2009/04/09 PHP
php设计模式 Singleton(单例模式)
2011/06/26 PHP
PHP中捕获超时事件的方法实例
2015/02/12 PHP
Jquery AJAX 用于计算点击率(统计)
2010/06/30 Javascript
基于JQuery的Select选择框的华丽变身
2011/08/23 Javascript
复选框全选与全不选操作实现思路
2013/08/18 Javascript
JS调试必备的5个debug技巧
2014/03/07 Javascript
Javascript添加监听与删除监听用法详解
2014/12/19 Javascript
JavaScript原生xmlHttp与jquery的ajax方法json数据格式实例
2015/12/04 Javascript
JavaScript修改作用域外变量的方法
2016/03/25 Javascript
Jquery揭秘系列:ajax原生js实现详解(推荐)
2016/06/08 Javascript
jquery+ajax实现直接提交表单实例分析
2016/06/17 Javascript
jQuery.datatables.js插件用法及api实例详解
2016/10/28 Javascript
javascript 操作cookies详解及实例
2017/02/22 Javascript
Angular.js前台传list数组由后台spring MVC接收数组示例代码
2017/07/31 Javascript
jQuery 导航自动跟随滚动的实现代码
2018/05/30 jQuery
element-ui中的select下拉列表设置默认值方法
2018/08/24 Javascript
利用weixin-java-miniapp生成小程序码并直接返回图片文件流的方法
2019/03/29 Javascript
vue路由切换之淡入淡出的简单实现
2019/10/31 Javascript
[01:18]PWL开团时刻DAY4——圣剑与抢盾
2020/11/03 DOTA
python中使用smtplib和email模块发送邮件实例
2014/04/22 Python
Python中使用items()方法返回字典元素对的教程
2015/05/21 Python
TensorFlow实现RNN循环神经网络
2018/02/28 Python
Python入门学习指南分享
2018/04/11 Python
Appium+python自动化之连接模拟器并启动淘宝APP(超详解)
2019/06/17 Python
python序列类型种类详解
2020/02/26 Python
详解python爬取弹幕与数据分析
2020/11/14 Python
Python + opencv对拍照得到的图片进行背景去除的实现方法
2020/11/18 Python
用python批量移动文件
2021/01/14 Python
自我鉴定怎么写
2013/12/05 职场文书
中国梦口号
2014/06/13 职场文书
2014年局领导班子自身建设情况汇报
2014/11/21 职场文书
会计岗位职责范本
2015/04/02 职场文书
干部培训简讯
2015/07/20 职场文书
中秋晚会致辞
2015/07/31 职场文书
Pandas-DataFrame知识点汇总
2022/03/16 Python