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 ...
随机推荐
- elment ui 图片上传遇到的一些问题
图片上传返回200,message显示请上传图片 注意上图中的name字段要和服务器接受的name相同,这里我们是imgfile,默认name不是这个,所以要在el-upload组件上设置name属性 ...
- CSS_级联和继承
2016-11-06 <CSS入门经典>第七章 1.在HTML中使用CSS样式表的三种方式: (1)内联的样式表. eg:<em style="background-whi ...
- django之Ajax初识
Ajax准么说是用于Javascript与服务器端进行交互的,我们之前呢没有了解ajax也同样可以完成与服务器的交互,那么ajax的优势在哪里?首先ajax是异步交互的也就是说我们基本不会遇到卡顿现象 ...
- 2.1 mac下多版本jdk的安装和管理
之前已经安装过jdk8了,安装路径:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk 现在安装jdk10,下载后,双击dmg文件一直到安装完成,安装 ...
- centos找不到环境变量 -bash: ls: command not found
#在系统中输入命令,报如下错误: [root@a1 work]# ll-bash: ls: command not found #昨时解决办法:export PATH=/usr/local/sbin: ...
- 160多个android开源码汇总
第一部分 个性化控件(View) 主要介绍那些不错个性化的View,包含ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.Pro ...
- idea 集成sonarLint检查代码bugs
1.目标 idea集成sonar的代码检查,实现可以在提交代码前就检查你的代码,而不是将代码提交之后,之后再去检查. Sonar可以从以下七个维度检测代码质量,而作为开发人员至少需要处理前5种代码质量 ...
- 大疆无人机M100相关问题解决过程
1.遥控器升级问题 iOS端使用app升级,重复尝试了5次+,还是无法升级.卸载app重新安装,依旧是无法升级.使用Android app升级,一次搞定. 2.飞行器固件升级(云台别选错了) http ...
- nginx(二)支持websocket配置
在默认的配置nginx.conf文件中做如下配置改动 一.http域的设置 http { include mime.types; default_type application/octet-stre ...
- Tomcat线程池的深入理解
1.工作机制: Tomcat启动时如果没有请求过来,那么线程数(都是指线程池的)为0: 一旦有请求,Tomcat会初始化minSpareThreads设置的线程数: 2.线程池作用: Tomcat的线 ...