pymysql操作mysql
一、使用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的更多相关文章
- Python 3 进阶 —— 使用 PyMySQL 操作 MySQL
PyMySQL 是一个纯 Python 实现的 MySQL 客户端操作库,支持事务.存储过程.批量执行等. PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Py ...
- python 3.6 +pyMysql 操作mysql数据库
版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...
- flask + pymysql操作Mysql数据库
安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...
- PyMySQL操作mysql数据库(py3必学)
一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...
- pymysql操作mysql数据库
1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...
- 用pymysql操作MySQL数据库
工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...
- 使用pymysql 操作MySQL数据库
安装 pip install pymysql 注:连接前要有可使用的账户及有权限.可操作的数据库 先来一个栗子: import pymysql # 连接database conn = pymysql. ...
- 使用pymysql操作mysql数据库
PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...
- pymysql操作mysql的脚本示例
#!/usr/bin/env python#-*- coding:UTF-8 -*- from multiprocessing import Process , Queuefrom queue imp ...
随机推荐
- CSS_选择符
2016-10-28 <CSS入门经典>第五章 以下提示注意事项: 1.如何选择使用id选择符还是class选择符:当确信id选择符在页面的唯一性时,就可以使用id选择符. 2.通用选择符 ...
- Filter(1)—基础知识
一.过滤器(Filter) 1.概述: JavaWeb的一个重要组件,可以对请求和响应拦截 Filter的基本功能是对Servlet容器调用Servlet过程中进行拦截,从而在Servlet进行响应处 ...
- [Java代码] Java用pinyin4j根据汉语获取各种格式和需求的拼音
pinyin4j是一个功能强悍的汉语拼音工具包,主要是从汉语获取各种格式和需求的拼音,功能强悍,下面看看如何使用pinyin4j.下面介绍用pinyin4j来做的一个根据汉语获取各种格式和需求的拼音d ...
- Android的Databinding-资源绑定
databinding还能对布局的资源文件进行绑定. <data class="ResourceBinding"> <variable name="la ...
- Spring Boot 之httpClient使用
版权声明:本文为博主原创文章,转载时请在文章最前方附上本文地址. https://blog.csdn.net/qq_35033270/article/details/80112085 超文本传输协议( ...
- 深入理解C++内存管理机制
关于C++的内存处理,可分为三大块,分别是: (一)内存管理机制 (二)内存泄露处理 (三)内存回收机制 这篇文章将就(一)内存管理机制 进行深入探讨,如有错误欢迎大家指正. C++的内存管理也可细分 ...
- Redis接口的调用
1.hiredis是redis数据库的C接口,目录为/redis-3.2.6/deps/hiredis 2.示例代码如下: #include <stdio.h> #include < ...
- virltualbox 升级之后 苹果虚拟机报The installed support driver doesn't match the version of the user解决方案
1.反安装virtualbox后,不要重启 2.删除virtualbox的安装目录 3.进入%userprofile% 目录 (比如: C:\users\me) 删除 .VirtualBox Virt ...
- linux apache2部署php
apache2 doc http://blog.csdn.net/actor1999/article/details/44802519 #apache sudo apt-get install apa ...
- logback配置异步日志
<appender name="FILE" class= "ch.qos.logback.core.rolling.RollingFileAppender" ...