python使用pymysql实现操作mysql


Posted in Python onSeptember 13, 2016

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。

适用环境

python版本 >=2.6或3.3

mysql版本>=4.1

安装

可以使用pip安装也可以手动下载安装。

使用pip安装,在命令行执行如下命令:

pip install PyMySQL

手动安装,请先下载。下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。

其中的X.X是版本(目前可以获取的最新版本是0.6.6)。

下载后解压压缩包。在命令行中进入解压后的目录,执行如下的指令:

python setup.py install

建议使用pip安装。

使用示例

连接数据库如下:

import pymysql.cursors
 
# Connect to the database
connection = pymysql.connect(host='127.0.0.1',
               port=3306,
               user='root',
               password='zhyea.com',
               db='employees',
               charset='utf8mb4',
               cursorclass=pymysql.cursors.DictCursor)

也可以使用字典进行连接参数的管理,我觉得这样子更优雅一些:

import pymysql.cursors
 
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
 
# Connect to the database
connection = pymysql.connect(**config)

插入数据:

执行sql语句前需要获取cursor,因为配置默认自动提交,故在执行sql语句后需要主动commit,最后不要忘记关闭连接:

from datetime import date, datetime, timedelta
import pymysql.cursors
 
#连接配置信息
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
# 创建连接
connection = pymysql.connect(**config)
 
# 获取明天的时间
tomorrow = datetime.now().date() + timedelta(days=1)
 
# 执行sql语句
try:
  with connection.cursor() as cursor:
    # 执行sql语句,插入记录
    sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'
    cursor.execute(sql, ('Robin', 'Zhyea', tomorrow, 'M', date(1989, 6, 14)));
  # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
  connection.commit()
 
finally:
  connection.close();

执行查询:

import datetime
import pymysql.cursors
 
#连接配置信息
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
# 创建连接
connection = pymysql.connect(**config)
 
# 获取雇佣日期
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(2016, 12, 31)
 
# 执行sql语句
try:
  with connection.cursor() as cursor:
    # 执行sql语句,进行查询
    sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'
    cursor.execute(sql, (hire_start, hire_end))
    # 获取查询结果
    result = cursor.fetchone()
    print(result)
  # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
  connection.commit()
 
finally:
  connection.close();

这里的查询支取了一条查询结果,查询结果以字典的形式返回:

从结果集中获取指定数目的记录,可以使用fetchmany方法:

result = cursor.fetchmany(2)

不过不建议这样使用,最好在sql语句中设置查询的记录总数。

获取全部结果集可以使用fetchall方法:

result = cursor.fetchall()

因为只有两条记录,所以上面提到的这两种查询方式查到的结果是一样的:

[{'last_name': 'Vanderkelen', 'hire_date': datetime.date(2015, 8, 12), 'first_name': 'Geert'}, {'last_name': 'Zhyea', 'hire_date': datetime.date(2015, 8, 21), 'first_name': 'Robin'}]

在django中使用

在django中使用是我找这个的最初目的。目前同时支持python3.4、django1.8的数据库backend并不好找。这个是我目前找到的最好用的。

设置DATABASES和官方推荐使用的MySQLdb的设置没什么区别:

DATABASES = {
   'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mytest',
        'USER': 'root',
        'PASSWORD': 'zhyea.com',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
 

关键是这里:我们还需要在站点的__init__.py文件中添加如下的内容:

import pymysql
pymysql.install_as_MySQLdb()

最后给大家附上pymysql实现增删改查的代码,希望大家能够喜欢

#!/usr/bin/python
#coding:gbk
import pymysql
from builtins import int

#将MysqlHelper的几个函数写出来

def connDB():               #连接数据库
  conn=pymysql.connect(host="localhost",user="root",passwd="zx69728537",db="student");
  cur=conn.cursor();
  return (conn,cur);

def exeUpdate(conn,cur,sql):        #更新或插入操作
  sta=cur.execute(sql);
  conn.commit();
  return (sta);

def exeDelete(conn,cur,IDs):        #删除操作
  sta=0;
  for eachID in IDs.split(' '):
    sta+=cur.execute("delete from students where Id=%d"%(int(eachID)));
  conn.commit();
  return (sta);
    
def exeQuery(cur,sql):           #查找操作
  cur.execute(sql);
  return (cur);
  
def connClose(conn,cur):          #关闭连接,释放资源
  cur.close();
  conn.close();

result=True;
print("请选择以上四个操作:1、修改记录,2、增加记录,3、查询记录,4、删除记录.(按q为退出)");
conn,cur=connDB();
number=input();
while(result):
  if(number=='q'):
    print("结束操作");
    break;
  elif(int(number)==1):
    sql=input("请输入更新语句:");
    try:
      exeUpdate(conn, cur, sql);
      print("更新成功");
    except Exception:
      print("更新失败");
      raise;
  elif(int(number)==2):
      sql=input("请输入新增语句:");
      try:
        exeUpdate(conn, cur, sql);
        print("新增成功");
      except Exception:
        print("新增失败");
        raise;
  elif(int(number)==3):
    sql=input("请输入查询语句:");
    try:
      cur=exeQuery(cur, sql);
      for item in cur:
        print("Id="+str(item[0])+" name="+item[1]);
    except Exception:
      print("查询出错");
      raise;
  elif(int(number)==4):
    Ids=input("请输入Id,并用空格隔开");
    try:
      exeDelete(conn, cur, Ids);
      print("删除成功");
    except Exception:
      print("删除失败");
      raise;
  else:
    print("非法输入,将结束操作!");
    result=False;
    break;
  print("请选择以上四个操作:1、修改记录,2、增加记录,3、查询记录,4、删除记录.(按q为退出)");
  number=input("请选择操作");
Python 相关文章推荐
python 获取et和excel的版本号
Apr 09 Python
python类参数self使用示例
Feb 17 Python
老生常谈Python序列化和反序列化
Jun 28 Python
速记Python布尔值
Nov 09 Python
Python中用psycopg2模块操作PostgreSQL方法
Nov 28 Python
Python iter()函数用法实例分析
Mar 17 Python
Python使用matplotlib实现的图像读取、切割裁剪功能示例
Apr 28 Python
python的常用模块之collections模块详解
Dec 06 Python
在python中logger setlevel没有生效的解决
Feb 21 Python
python脚本第一行如何写
Aug 30 Python
Python unittest discover批量执行代码实例
Sep 08 Python
Django url 路由匹配过程详解
Jan 22 Python
python实现可以断点续传和并发的ftp程序
Sep 13 #Python
Python安装第三方库及常见问题处理方法汇总
Sep 13 #Python
Python中操作mysql的pymysql模块详解
Sep 13 #Python
python常用函数详解
Sep 13 #Python
python如何查看系统网络流量的信息
Sep 12 #Python
Python爬取三国演义的实现方法
Sep 12 #Python
python 读写、创建 文件的方法(必看)
Sep 12 #Python
You might like
判断是否为指定长度内字符串的php函数
2010/02/16 PHP
php中用foreach来操作数组的代码
2011/07/17 PHP
详解PHP队列的实现
2019/03/14 PHP
Aster vs KG BO3 第一场2.19
2021/03/10 DOTA
js 替换功能函数,用正则表达式解决,js的全部替换
2010/12/08 Javascript
JavaScript中为元素加上name属性的方法
2011/05/09 Javascript
Js实现手机发送验证码时按钮延迟操作
2014/06/20 Javascript
防止登录页面出现在frame中js代码
2014/07/22 Javascript
JS实现鼠标滑过链接改变网页背景颜色的方法
2015/10/20 Javascript
JS解决iframe之间通信和自适应高度的问题
2016/08/24 Javascript
Angular.js之作用域scope'@','=','&'实例详解
2017/02/28 Javascript
了解JavaScript中let语句
2019/05/30 Javascript
基于Express框架使用POST传递Form数据
2019/08/10 Javascript
JS实现简单贪吃蛇小游戏
2020/10/28 Javascript
使用python获取CPU和内存信息的思路与实现(linux系统)
2014/01/03 Python
Python彩色化Linux的命令行终端界面的代码实例分享
2016/07/02 Python
使用Python对MySQL数据操作
2017/04/06 Python
Python中单、双下划线的区别总结
2017/12/01 Python
java中两个byte数组实现合并的示例
2018/05/09 Python
Python操作Sql Server 2008数据库的方法详解
2018/05/17 Python
python实现pdf转换成word/txt纯文本文件
2018/06/07 Python
对tensorflow 的模型保存和调用实例讲解
2018/07/28 Python
Python实现12306火车票抢票系统
2019/07/04 Python
python3反转字符串的3种方法(小结)
2019/11/07 Python
Python列表解析操作实例总结
2020/02/26 Python
Python字符串格式化f-string多种功能实现
2020/05/07 Python
matplotlib制作雷达图报错ValueError的实现
2021/01/05 Python
html5 拖拽上传图片实例演示
2013/04/01 HTML / CSS
广州喜创信息技术有限公司JAVA软件工程师笔试题
2012/10/17 面试题
毕业生医学检验求职信
2013/10/16 职场文书
关于祖国的演讲稿
2014/05/04 职场文书
儿童生日会策划方案
2014/05/15 职场文书
护士找工作求职信
2014/07/02 职场文书
党员自我评议个人对照检查材料
2014/09/16 职场文书
浅谈Redis主从复制以及主从复制原理
2021/05/29 Redis
一文带你探究MySQL中的NULL
2021/11/11 MySQL