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 ...
随机推荐
- 词向量保存为txt
model.wv.save_word2vec_format('w2v_mod.txt',binary=False)
- web端设计和web前端开发 的区别
- pygame-KidsCanCode系列jumpy-part9-使用spritesheet
做过前端的兄弟应该都知道css sprite(也称css精灵),这是一种常用的减少http请求次数的优化手段.把很多小图拼成一张大图,只加载1次,然后用css定位到不区的区域,从而展示不同的图片.游戏 ...
- Spring Boot 之httpClient使用
版权声明:本文为博主原创文章,转载时请在文章最前方附上本文地址. https://blog.csdn.net/qq_35033270/article/details/80112085 超文本传输协议( ...
- 发现一个“佛系记账本”
因为这是一款微信小程序,张小龙大力推崇的"用完即走"完美地适合记账应用. 不用下载.不用安装.不用注册.不用各种授权,只要从微信进入,就能记账,账本只与微信关联. 换手机.换PAD ...
- Velocity日期格式化
1.pom.xml添加依赖 <dependency> <groupId>velocity-tools</groupId> <artifactId>vel ...
- [Vuex] Split Vuex Store into Modules using TypeScript
When the Vuex store grows, it can have many mutations, actions and getters, belonging to different c ...
- Android 获取Activity当前view
View cv = getWindow().getDecorView(); 来自为知笔记(Wiz)
- Linux下通过server-status监控性能
Linux下通过server-status监控性能 前提:安装好Apache,在opt/路径下 查看Apache的工作模式 可以知道是 prefork.c模式 配置server-status 性能 进 ...
- Unity应用架构设计(8)——使用ServiceLocator实现对象的注入
对象的 『注入』 是企业级软件开发经常听到的术语.如果你是一个 Java 程序员,一定对注入有着深刻的映像.不管是SSH框架还是SSM框架,Spring 全家桶永远是绕不过去的弯.通过依赖注入,可以有 ...