适用环境

python版本 >=2.6或3.3

mysql版本>=4.1

安装

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

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

1
pip install PyMySQL

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

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

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

 
1
python setup.py install

建议使用pip安装。

使用示例

连接数据库如下:

 
1
2
3
4
5
6
7
8
9
10
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)

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

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,最后不要忘记关闭连接:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();

执行查询:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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方法:

 
1
result = cursor.fetchmany(2)

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

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

 
1
result = cursor.fetchall()

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

 
1
[{'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的设置没什么区别:

 
1
2
3
4
5
6
7
8
9
10
DATABASES = {
   'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mytest',
        'USER': 'root',
        'PASSWORD': 'zhyea.com',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

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

 
1
2
import pymysql
pymysql.install_as_MySQLdb()

pymysql 使用的更多相关文章

  1. pyMysql

    本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...

  2. Python 3.x 连接数据库(pymysql 方式)

    ==================pymysql=================== 由于 MySQLdb 模块还不支持 Python3.x,所以 Python3.x 如果想连接MySQL需要安装 ...

  3. Python中操作mysql的pymysql模块详解

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

  4. 杂项之pymysql连接池

    杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普通的pymysql插入100W条 ...

  5. Python3中使用PyMySQL连接Mysql

    Python3中使用PyMySQL连接Mysql 在Python2中连接Mysql数据库用的是MySQLdb,在Python3中连接Mysql数据库用的是PyMySQL,因为MySQLdb不支持Pyt ...

  6. Python之路-python(mysql介绍和安装、pymysql、ORM sqlachemy)

    本节内容 1.数据库介绍 2.mysql管理 3.mysql数据类型 4.常用mysql命令 创建数据库 外键 增删改查表 5.事务 6.索引 7.python 操作mysql 8.ORM sqlac ...

  7. python pymysql和orm

    pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1. 安装 管理员打开cmd,切换到python的安装路径,进入到Scripts目录下(如:C:\Users\A ...

  8. python成长之路【第十三篇】:Python操作MySQL之pymysql

    对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎 ...

  9. (转)pymysql 连接mysql数据库---不支持中文解决

    往数据库里插入中文时出现异常:UnicodeEncodeError: 'latin-1' codec can't encode characters 就是编码的问题,pymysql默认的编码是lati ...

  10. 循序渐进Python3(十)-- 1 -- pymysql

    使用pymsql 模块操作数据库 #!/usr/bin/env python , ),()]), user='root', passwd='123456', db='test')# 创建游标curso ...

随机推荐

  1. truncate、delete、drop

    相同点: 1.三者共同点: truncate.不带where字句的delete.drop都会删除表内的数据 2.drop.truncate的共同点: drop.truncate都得DDL语句(数据库定 ...

  2. 【JZOJ6346】ZYB和售货机

    description analysis 其实这个连出来的东西叫基环内向树 先考虑很多森林的情况,也就是树根连回自己 明显树根物品是可以被取完的,那么买树根的价钱要是儿子中价钱最小的那个 或者把那个叫 ...

  3. 登录操作(方法一:设置flag标志位)

    登录操作(方法一:设置flag标志位) user_name="star"passwoed='123'passed_authentication=Falsecount=0for i ...

  4. 概率dp——处理分母为0的情况hdu3853

    很水的题,但要注意的是必须处理分母为0的情况 #include<bits/stdc++.h> using namespace std; ; ; ],e[maxn][maxn]; int r ...

  5. spring 家族

    spring家族:spring.springMVC .springBoots springCloud

  6. eclipse配置外部工具利用javah编译生成头文件

    1. 点击eclipse工具栏外部工具按钮,打开配置外部工具 2. 新建一个启动配置,起名为Generate C and C++ Header File,按照下图配置好相应的参数 3. 运行该工具时, ...

  7. HttpUrlConnection使用详解--转AAAAA

    http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpConnection.html HttpUr ...

  8. IENumerable_Test

    using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...

  9. PAT甲级——A1122 Hamiltonian Cycle【25】

    The "Hamilton cycle problem" is to find a simple cycle that contains every vertex in a gra ...

  10. Ubuntu环境下java.lang.SecurityException: Invalid signature file digest for Manifest main attributes

    一.问题描述 Ubuntu环境中,将maven项目打包成jar包传到服务器中后运行以下指令: $ java -cp my.jar com.myproject.Main 遇到报错: java.lang. ...