Python 操作MySQL详解及实例


Posted in Python onApril 30, 2017

Python 操作MySQL详解及实例

使用Python进行MySQL的库主要有三个,Python-MySQL(更熟悉的名字可能是MySQLdb),PyMySQL和SQLAlchemy。

Python-MySQL资格最老,核心由C语言打造,接口精炼,性能最棒,缺点是环境依赖较多,安装复杂,近两年已停止更新,只支持Python2,不支持Python3。

PyMySQL为替代Python-MySQL而生,纯python打造,接口与Python-MySQL兼容,安装方便,支持Python3。

SQLAlchemy是一个ORM框架,它并不提供底层的数据库操作,而是要借助于MySQLdb、PyMySQL等第三方库来完成,目前SQLAlchemy在Web编程领域应用广泛。

本文主要介绍PyMySQL的正确使用方法,示例代码都是选自实战项目。

安装

简单的方式:

pip install pymysql

如果无法联网,需要进行离线安装,例如:

pip install pymysql-x.x.x.tar.gz

导入

import pymysql

连接

def connect_wxremit_db():
  return pymysql.connect(host='10.123.5.28',
              port=3306,
              user='root',
              password='root1234',
              database='db_name',
              charset='latin1')

查询

def query_country_name(cc2):
  sql_str = ("SELECT Fcountry_name_zh"
        + " FROM t_country_code"
        + " WHERE Fcountry_2code='%s'" % (cc2))
  logging.info(sql_str)

  con = mysql_api.connect_wxremit_db()
  cur = con.cursor()
  cur.execute(sql_str)
  rows = cur.fetchall()
  cur.close()
  con.close()

  assert len(rows) == 1, 'Fatal error: country_code does not exists!'
  return rows[0][0]

简单插入

def insert_file_rec(self, file_name, file_md5):
    con = mysql_api.connect_wxremit_db()
    cur = con.cursor()
    try:
      sql_str = ("INSERT INTO t_forward_file (Ffile_name, Ffile_md5)", 
            + " VALUES ('%s', '%s')" % (file_name, file_md5))
      cur.execute(sql_str)
      con.commit()
    except:
      con.rollback()
      logging.exception('Insert operation error')
      raise
    finally:
      cur.close()
      con.close()

批量插入

remit_ids = [('1234', 'CAD'), ('5678', 'HKD')]

con = mysql_api.connect_wxremit_db()
    cur = con.cursor()
    try:
        cur.executemany("INSERT INTO t_order (Fremit_id, Fcur_type, Fcreate_time"
                        + " VALUES (%s, %s, now())", new_items)
        assert cur.rowcount == len(remit_ids), 'my error message'
        con.commit()
    except Exception as e:
        con.rollback()
        logging.exception('Insert operation error')
    finally:
        cur.close()
        con.close()

更新

def update_refund_trans(self, remit_id):
    con = mysql_api.connect_wxremit_db()
    cur = con.cursor()
    try:
      sql_str = ("SELECT Fremit_id"
            + " FROM t_wxrefund_trans"
            + " WHERE Fremit_id='%s'" % remit_id
            + " FOR UPDATE")
      logging.info(sql_str)

      cur.execute(sql_str)
      assert cur.rowcount == 1, 'Fatal error: The wx-refund record be deleted!'

      sql_str = ("UPDATE t_wxrefund_trans"
            + " SET Fcheck_amount_flag=1"
            + ", Fmodify_time=now()"
            + " WHERE Fremit_id='%s'" % remit_id
      logging.info(sql_str)
      cur.execute(sql_str)

      assert cur.rowcount == 1, 'The number of affected rows not equal to 1'
      con.commit()
    except:
      con.rollback()
      logging.exception('Update operation error')
      raise
    finally:
      cur.close()
      con.close()

PyMySQL已经相当成熟,和Python-MySQL一样,它在很多Linux发行版本中都是可选的安装组件。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Python 相关文章推荐
Python制作简单的网页爬虫
Nov 22 Python
Python机器学习之K-Means聚类实现详解
Feb 22 Python
详解基于django实现的webssh简单例子
Jul 17 Python
Python流行ORM框架sqlalchemy安装与使用教程
Jun 04 Python
django基础学习之send_mail功能
Aug 07 Python
基于python的selenium两种文件上传操作实现详解
Sep 19 Python
python实现提取str字符串/json中多级目录下的某个值
Feb 27 Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 Python
Keras: model实现固定部分layer,训练部分layer操作
Jun 28 Python
Python3使用 GitLab API 进行批量合并分支
Oct 15 Python
python实现简易名片管理系统
Apr 11 Python
Python使用BeautifulSoup4修改网页内容
May 20 Python
浅谈function(函数)中的动态参数
Apr 30 #Python
python脚本爬取字体文件的实现方法
Apr 29 #Python
Python在图片中添加文字的两种方法
Apr 29 #Python
Python实现对字符串的加密解密方法示例
Apr 29 #Python
Python实现通过文件路径获取文件hash值的方法
Apr 29 #Python
python基于pyDes库实现des加密的方法
Apr 29 #Python
Python简单实现Base64编码和解码的方法
Apr 29 #Python
You might like
《Pokemon Sword·Shield》系列WEB动画《薄明之翼》第2话声优阵容公开!
2020/03/06 日漫
php str_replace的替换漏洞
2008/03/15 PHP
APACHE的AcceptPathInfo指令使用介绍
2013/01/18 PHP
关于PHP模板Smarty的初级使用方法以及心得分享
2013/06/21 PHP
JS实现的省份级联实例代码
2013/06/24 Javascript
javascript的内存管理详解
2013/08/07 Javascript
Jquery取得iframe下内容的方法
2013/11/18 Javascript
面向切面编程(AOP)的理解
2015/05/01 Javascript
全面详细的jQuery常见开发技巧手册
2016/02/21 Javascript
JavaScript实现256色转灰度图
2017/02/22 Javascript
老生常谈js中0到底是 true 还是 false
2017/03/08 Javascript
ionic2屏幕适配实现适配手机、平板等设备的示例代码
2017/08/11 Javascript
vue用addRoutes实现动态路由的示例
2017/09/15 Javascript
第一个Vue插件从封装到发布
2017/11/22 Javascript
详解如何使用babel进行es6文件的编译
2018/05/29 Javascript
VUE 解决mode为history页面为空白的问题
2019/11/01 Javascript
jquery轮播图插件使用方法详解
2020/07/31 jQuery
基于javascript实现放大镜特效
2020/12/03 Javascript
小米5s微信跳一跳小程序python源码
2018/01/08 Python
python 读取DICOM头文件的实例
2018/05/07 Python
Python3之简单搭建自带服务器的实例讲解
2018/06/04 Python
python实现在遍历列表时,直接对dict元素增加字段的方法
2019/01/15 Python
python自动化unittest yaml使用过程解析
2020/02/03 Python
解决pyqt5异常退出无提示信息的问题
2020/04/08 Python
python实点云分割k-means(sklearn)详解
2020/05/28 Python
英国最大的电脑零售连锁店集团:PC World
2016/10/10 全球购物
戴森香港官方网站:Dyson香港
2021/02/11 全球购物
高一自我鉴定
2013/12/17 职场文书
安全保证书范文
2014/04/29 职场文书
爱护公物标语
2014/06/24 职场文书
教师学习三严三实心得体会
2014/10/13 职场文书
2014年民主评议党员工作总结
2014/12/02 职场文书
自荐信格式范文
2015/03/04 职场文书
2019中小学生安全过暑期倡议书
2019/06/24 职场文书
Redis 配置文件重要属性的具体使用
2021/05/20 Redis
Python加密与解密模块hashlib与hmac
2022/06/05 Python