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采用socket模拟TCP通讯的实现方法
Nov 19 Python
Python ValueError: invalid literal for int() with base 10 实用解决方法
Jun 21 Python
python2.7安装图文教程
Mar 13 Python
详解python多线程、锁、event事件机制的简单使用
Apr 27 Python
Python2包含中文报错的解决方法
Jul 09 Python
利用pandas进行大文件计数处理的方法
Jul 25 Python
在Python 中同一个类两个函数间变量的调用方法
Jan 31 Python
Python中用pyinstaller打包时的图标问题及解决方法
Feb 17 Python
PHP基于phpqrcode类库生成二维码过程解析
May 28 Python
无需压缩软件,用python帮你操作压缩包
Aug 17 Python
Python页面加载的等待方式总结
Feb 28 Python
asyncio异步编程之Task对象详解
Mar 13 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 面试碰到过的问题 在此做下记录
2011/06/09 PHP
基于PHP实现商品成交时发送短信功能
2016/05/11 PHP
smarty的section嵌套循环用法示例
2016/05/28 PHP
php微信开发之百度天气预报
2016/11/18 PHP
javascript import css实例代码
2008/07/18 Javascript
jquery1.4.2 for Visual studio 2010 模板文件
2010/07/14 Javascript
javaScript 利用闭包模拟对象的私有属性
2011/12/29 Javascript
JS/jQuery实现默认显示部分文字点击按钮显示全部内容
2013/05/13 Javascript
flash调用js中的方法,让js传递变量给flash的办法及思路
2013/08/07 Javascript
javascript遍历控件实例详细解析
2014/01/10 Javascript
js实现跨域的多种方法
2015/12/25 Javascript
Kendo Grid editing 自定义验证报错提示的解决方法
2016/11/18 Javascript
Angular2库初探
2017/03/01 Javascript
jQuery插件echarts去掉垂直网格线用法示例
2017/03/03 Javascript
分享一个精简的vue.js 图片lazyload插件实例
2017/03/13 Javascript
node.js中path路径模块的使用方法实例分析
2020/02/13 Javascript
javascript实现拖拽碰撞检测
2020/03/12 Javascript
Vue-CLI 3 scp2自动部署项目至服务器的方法
2020/07/24 Javascript
[01:57]DOTA2上海特锦赛小组赛解说单车采访花絮
2016/02/27 DOTA
Python查找相似单词的方法
2015/03/05 Python
解决vscode python print 输出窗口中文乱码的问题
2018/12/03 Python
Python模拟百度自动输入搜索功能的实例
2019/02/14 Python
Python装饰器限制函数运行时间超时则退出执行
2019/04/09 Python
在Django admin中编辑ManyToManyField的实现方法
2019/08/09 Python
Python selenium的基本使用方法分析
2019/12/21 Python
Django扫码抽奖平台的配置过程详解
2021/01/14 Python
详解python3 GUI刷屏器(附源码)
2021/02/18 Python
在HTML5 Canvas中放入图片和保存为图片的方法
2014/05/03 HTML / CSS
木马的传播途径主要有哪些
2016/04/08 面试题
建筑文秘专业个人求职信范文
2013/12/28 职场文书
公司同意接收函
2014/01/13 职场文书
yy司仪主持词
2014/03/22 职场文书
机械系毕业生求职信
2014/05/28 职场文书
倡议书格式
2014/08/30 职场文书
留学推荐信怎么写
2015/03/26 职场文书
MySQL的存储函数与存储过程的区别解析
2022/04/08 MySQL