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 分析Nginx访问日志并保存到MySQL数据库实例
Mar 13 Python
彻底理解Python list切片原理
Oct 27 Python
python生成二维码的实例详解
Oct 29 Python
Python中存取文件的4种不同操作
Jul 02 Python
Pycharm+Scrapy安装并且初始化项目的方法
Jan 15 Python
浅析python的Lambda表达式
Feb 27 Python
python实现对图片进行旋转,放缩,裁剪的功能
Aug 07 Python
将Python文件打包成.EXE可执行文件的方法
Aug 11 Python
python、PyTorch图像读取与numpy转换实例
Jan 13 Python
基于python代码批量处理图片resize
Jun 04 Python
Python虚拟环境的创建和包下载过程分析
Jun 19 Python
pytorch 实现变分自动编码器的操作
May 24 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
php 变量未定义等错误的解决方法
2011/01/12 PHP
PHP输入流php://input介绍
2012/09/18 PHP
php版小黄鸡simsimi聊天机器人接口分享
2014/01/26 PHP
Smarty模板学习笔记之Smarty简介
2014/05/20 PHP
php+mysqli使用预处理技术进行数据库查询的方法
2015/01/28 PHP
fsockopen pfsockopen函数被禁用,SMTP发送邮件不正常的解决方法
2015/09/20 PHP
JS小功能(onmouseover实现选择月份)实例代码
2013/11/28 Javascript
javascript元素动态创建实现方法
2015/05/13 Javascript
详解Javacript和AngularJS中的Promises
2016/02/09 Javascript
H5上传本地图片并预览功能
2017/05/08 Javascript
Angular 4中如何显示内容的CSS样式示例代码
2017/11/06 Javascript
Vue-Router实现组件间跳转的三种方法
2017/11/07 Javascript
webpack配置打包后图片路径出错的解决
2018/04/26 Javascript
对vue中v-on绑定自定事件的实例讲解
2018/09/06 Javascript
Python中的异常处理简明介绍
2015/04/13 Python
在Python中操作时间之strptime()方法的使用
2020/12/30 Python
Python之Web框架Django项目搭建全过程
2017/05/02 Python
关于反爬虫的一些简单总结
2017/12/13 Python
利用python提取wav文件的mfcc方法
2019/01/09 Python
python中append实例用法总结
2019/07/30 Python
softmax及python实现过程解析
2019/09/30 Python
使用python远程操作linux过程解析
2019/12/04 Python
Python序列化pickle模块使用详解
2020/03/05 Python
美国葡萄酒网上商店:Martha Stewart Wine Co.
2019/03/17 全球购物
印度尼西亚最好的小工具在线商店:Erafone.com
2019/03/26 全球购物
远东集团网络工程师面试题
2014/10/20 面试题
自考毕业自我鉴定范文
2013/10/27 职场文书
英语专业推荐信
2013/11/16 职场文书
博士生入学考试推荐信
2013/11/17 职场文书
校园歌手大赛策划书
2014/01/17 职场文书
母亲七十大寿答谢词
2014/01/18 职场文书
人事助理自荐信
2014/02/02 职场文书
出纳工作检讨书范文
2014/12/27 职场文书
小学运动会宣传稿
2015/07/23 职场文书
如何书写邀请函?
2019/06/24 职场文书
退休劳动合同怎么写?
2019/10/25 职场文书