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之变量和参数
Oct 10 Python
仅用500行Python代码实现一个英文解析器的教程
Apr 02 Python
python调用c++ ctype list传数组或者返回数组的方法
Feb 13 Python
解决python3.5 正常安装 却不能直接使用Tkinter包的问题
Feb 22 Python
python安装numpy和pandas的方法步骤
May 27 Python
对Python强大的可变参数传递机制详解
Jun 13 Python
使用python爬取微博数据打造一颗“心”
Jun 28 Python
python实现树的深度优先遍历与广度优先遍历详解
Oct 26 Python
Python自动采集微信联系人的实现示例
Feb 28 Python
python logging通过json文件配置的步骤
Apr 27 Python
keras中模型训练class_weight,sample_weight区别说明
May 23 Python
opencv 图像滤波(均值,方框,高斯,中值)
Jul 08 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相当简单的分页类
2008/10/02 PHP
PHP 进程锁定问题分析研究
2009/11/24 PHP
PHP中的函数嵌套层数限制分析
2011/06/13 PHP
PHP的array_diff()函数在处理大数组时的效率问题
2011/11/27 PHP
php简单socket服务器客户端代码实例
2015/05/18 PHP
PHP数字前补0的自带函数sprintf 和number_format的用法(详解)
2017/02/06 PHP
Mac系统下安装PHP Xdebug
2018/03/30 PHP
JavaScript中“+=”的应用
2007/02/02 Javascript
基于jQuery的弹出警告对话框美化插件(警告,确认和提示)
2010/06/10 Javascript
一个关于javascript匿名函数的问题分析
2012/03/30 Javascript
extjs tabpanel限制选项卡数量实现思路及代码
2013/04/02 Javascript
利用javascript数组长度循环数组内所有元素
2013/12/27 Javascript
window.showModalDialog()返回值的学习心得总结
2014/01/07 Javascript
js动画效果制件让图片组成动画代码分享
2014/01/14 Javascript
js中arguments,caller,callee,apply的用法小结
2014/01/28 Javascript
jQuery 写的简单打字游戏可以提示正确和错误的次数
2014/07/01 Javascript
bmob js-sdk 在vue中的使用教程
2018/01/21 Javascript
jQuery实现的简单拖拽功能示例【测试可用】
2018/08/14 jQuery
vue组件通信传值操作示例
2019/01/08 Javascript
vue计算属性computed、事件、监听器watch的使用讲解
2019/01/21 Javascript
mpvue小程序循环动画开启暂停的实现方法
2019/05/15 Javascript
微信小程序 行的删除和增加操作实现详解
2019/09/29 Javascript
webpack DllPlugin xxx is not defined解决办法
2019/12/13 Javascript
在Python程序中操作文件之isatty()方法的使用教程
2015/05/24 Python
使用Python对IP进行转换的一些操作技巧小结
2015/11/09 Python
基于python的七种经典排序算法(推荐)
2016/12/08 Python
Python高斯消除矩阵
2019/01/02 Python
利用python numpy+matplotlib绘制股票k线图的方法
2019/06/26 Python
Python调用钉钉自定义机器人的实现
2020/01/03 Python
Pandas将列表(List)转换为数据框(Dataframe)
2020/04/24 Python
python如何输出反斜杠
2020/06/18 Python
HTML5 语音搜索(淘宝店语音搜素)
2013/01/03 HTML / CSS
商铺租房协议书范本
2014/12/04 职场文书
女性健康知识讲座主持词
2015/07/04 职场文书
探讨Java中的深浅拷贝问题
2021/06/26 Java/Android
缓存替换策略及应用(以Redis、InnoDB为例)
2021/07/25 Redis