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语言的12个基础知识点小结
Jul 10 Python
python实现删除文件与目录的方法
Nov 10 Python
python通过BF算法实现关键词匹配的方法
Mar 13 Python
Python中pygame安装方法图文详解
Nov 11 Python
使用Python实现简单的服务器功能
Aug 25 Python
Python字符串逆序的实现方法【一题多解】
Feb 18 Python
在python中利用numpy求解多项式以及多项式拟合的方法
Jul 03 Python
简单了解python变量的作用域
Jul 30 Python
使用NumPy读取MNIST数据的实现代码示例
Nov 20 Python
Python 简单计算要求形状面积的实例
Jan 18 Python
Python制作简单的剪刀石头布游戏
Dec 10 Python
Python如何用re模块实现简易tokenizer
May 02 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
日本收入最高的漫画家:海贼王作者版税年收入高达8.45亿元
2020/03/04 日漫
php 调用远程url的六种方法小结
2009/11/02 PHP
php 目录遍历、删除 函数的使用介绍
2013/04/28 PHP
PHP 解决session死锁的方法
2013/06/20 PHP
Codeigniter整合Tank Auth权限类库详解
2014/06/12 PHP
php自定义类fsocket模拟post或get请求的方法
2015/07/31 PHP
JavaScript 学习点滴记录
2009/04/24 Javascript
filters.revealTrans.Transition使用方法小结
2010/08/19 Javascript
JavaScript字符串对象的concat方法实例(用于连接两个或多个字符串)
2014/10/16 Javascript
JavaScript组合拼接字符串的效率对比测试
2014/11/06 Javascript
深入浅出es6模板字符串
2017/08/26 Javascript
vue2.0使用swiper组件实现轮播效果
2017/11/27 Javascript
jquery判断滚动条距离顶部的距离方法
2018/09/05 jQuery
CKeditor富文本编辑器使用技巧之添加自定义插件的方法
2019/06/14 Javascript
JS防抖和节流实例解析
2019/09/24 Javascript
python脚本实现统计日志文件中的ip访问次数代码分享
2014/08/06 Python
wxpython中利用线程防止假死的实现方法
2014/08/11 Python
Python实现简易Web爬虫详解
2018/01/03 Python
python定位xpath 节点位置的方法
2019/08/27 Python
Python 中list ,set,dict的大规模查找效率对比详解
2019/10/11 Python
Pytest如何使用skip跳过执行测试
2020/08/13 Python
TensorFlow2.0使用keras训练模型的实现
2021/02/20 Python
amazeui页面分析之登录页面的示例代码
2020/08/25 HTML / CSS
社区十八大感言
2014/01/19 职场文书
英文演讲稿
2014/05/15 职场文书
国庆横幅标语
2014/10/08 职场文书
三严三实心得体会范文
2014/10/13 职场文书
专业见习报告范文
2014/11/03 职场文书
2014工程部年度工作总结
2014/12/17 职场文书
教师个人自我评价
2015/03/04 职场文书
2015年社区服务活动总结
2015/03/25 职场文书
项目经理岗位职责范本
2015/04/01 职场文书
入党积极分子半年考察意见
2015/06/02 职场文书
高考1977观后感
2015/06/04 职场文书
学校扫黄打非工作总结
2015/10/15 职场文书
MySQL 常见的数据表设计误区汇总
2021/06/07 MySQL