一、使用PyMySQL操作mysql数据库

适用环境

python版本 >=2.6或3.3
mysql版本>=4.1

安装

可以使用pip安装也可以手动下载安装。使用pip安装,在命令行执行如下命令:

pip install PyMySQL

手动安装,请先下载。下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。其中的X.X是版本。

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

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',
'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中使用

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

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

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

import pymysql
pymysql.install_as_MySQLdb()

pymysql操作mysql的更多相关文章

  1. Python 3 进阶 —— 使用 PyMySQL 操作 MySQL

    PyMySQL 是一个纯 Python 实现的 MySQL 客户端操作库,支持事务.存储过程.批量执行等. PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Py ...

  2. python 3.6 +pyMysql 操作mysql数据库

    版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...

  3. flask + pymysql操作Mysql数据库

    安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...

  4. PyMySQL操作mysql数据库(py3必学)

    一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...

  5. pymysql操作mysql数据库

    1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...

  6. 用pymysql操作MySQL数据库

    工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...

  7. 使用pymysql 操作MySQL数据库

    安装 pip install pymysql 注:连接前要有可使用的账户及有权限.可操作的数据库 先来一个栗子: import pymysql # 连接database conn = pymysql. ...

  8. 使用pymysql操作mysql数据库

    PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...

  9. pymysql操作mysql的脚本示例

    #!/usr/bin/env python#-*- coding:UTF-8 -*- from multiprocessing import Process , Queuefrom queue imp ...

随机推荐

  1. selenium3 文件系列之------读取properties文件

    一个eclipse工程会有很多配置文件,有的配置文件是写在properties里,也有写在xml文件里的.这个总结一下是自动化测试是如何读取properties文件. 一.准备config.prope ...

  2. GMA Round 1 简单的线性规划

    传送门 简单的线性规划 已知D(x,y)满足$\left\{\begin{matrix}x>-3\\ y>1\\ x+y<12\end{matrix}\right.$ 求$\frac ...

  3. sdn测量论文简介

    Prelude: Ensuring Inter-Domain Loop-Freedom in SDN-Enabled Networks 来源:APNet: The Asia-Pacific Works ...

  4. java新特性

    第一章:java8新特性 1.1 lambda表达式 1.2 Stream API 1.3 java8新特性总结 第二章:java9新特性 2.1 mac下多版本jdk的安装和管理 第三章:java1 ...

  5. Android开发中常见的设计模式 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. PornHub 正式发布 AI自动标注色情演员引擎

    http://igeekbar.com/igeekbar/post/501.htm Pornhub已经宣布推出一款全新的成人片识别引擎,这款引擎由AI驱动,使用计算机视觉技术自主检测和识别成人片内容以 ...

  7. dotnet ef

    dotnet ef migrations add <Name-of-Migration> dotnet ef database update

  8. 处理器 趣事 CPU/GPU/TPU/DPU/BPU

    有消息称,阿里巴巴达摩院正在研发一款神经网络芯片——Ali-NPU,主要运用于图像视频分析.机器学习等AI推理计算.按照设计,这款芯片性能将是目前市面上主流CPU.GPU架构AI芯片的10倍,而制造成 ...

  9. 找不到指定的 VM 安装:类型 标准 VM,名称 jre7

    问题背景是这样 原来使用的是jre7.0.55,后来为了安装使用 layabox IDE ,然后装了jdk_8u144 之后需要切换环境变量 之后java项目调试的时候重新设置了jdk,没问题. 直到 ...

  10. Python中的高级数据结构详解

    这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考 ...