一、使用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. JAVA分词包

    自然语言处理 中文分词 词性标注 命名实体识别 依存句法分析 关键词提取 自动摘要 短语提取 拼音 简繁转换 http://www.hankcs.com/nlp/ https://github.com ...

  2. 命令行添加subl命令

    添加了此命令后可以使用subl加文件或路径,就能通过命令行使用sublime text打开相应的文件或目录. 这里我的是MacOS,windows系统换路径就好. 第一步 sudo ln -s /Ap ...

  3. python之封装

    封装的主要原因是保护隐私,隔离复杂度 封装分为两个层面: 第一个层面的封装(什么都不用做):创建类和对象会分别创建二者的名称精简,我们只能用类名.或者obj.的方式去访问里面的名字,这本身就是一种分装 ...

  4. 【倍增】Tak and Hotels II @ABC044&ARC060/upcexam6463

    6463: Tak and Hotels II 时间限制: 1 Sec  内存限制: 128 MB 题目描述 N hotels are located on a straight line. The ...

  5. hbase.client.keyvalue.maxsize的默认值

    hbase的列族的最大值是在hbase配置里的hbase.client.keyvalue.maxsize,默认大小为10M,即 10485760 . http://eclecl1314-163-com ...

  6. 何谓sdk,何谓api

    狭义上的 SDK 指 Windows SDK,包括在 Windows 平台进行开发的一系列头文件和库文件以及命令行工具等. API 是 SDK 提供给用户的函数,即接口就是这个 SDK 提供给你用于应 ...

  7. xinetd服务

    xinetd(eXtended InterNET services daemon) 一.xinetd的功能介绍: xinetd提供类似于inetd+tcp_wrapper的功能,但是更加强大和安全.它 ...

  8. MultipartFile文件编码判断

    MultipartFile文件编码判断 搜索:Java 判断文件的字符集编码 https://blog.csdn.net/top_code/article/details/8891796 但是在Mul ...

  9. Android自定义控件实战——滚动选择器PickerView

    转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/38513301 手机里设置闹钟需要选择时间,那个选择时间的控件就是滚动选择器, ...

  10. Django 用户登陆访问限制 @login_required

    #用户登陆访问限制 from django.http import HttpResponseRedirect #只有登录了才能看到页面 #设置方法一:指定特定管理员才能访问 def main(requ ...