Python学习—数据库篇之pymysql
一、pymysql简介
对于Python操作MySQL主要使用两种方式:
- 原生模块 pymsql
- ORM框架 SQLAchemy
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。
二、简单使用
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
#执行sql操作
r = cursor.execute("insert into student(age,sex,class_no) values(16,'male',2)")
# r为执行sql语句后受影响的行数
print(r)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

三、增删改查
增
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor() # 增加一行数据
cursor.execute("insert into tb1(name,part) values('cdc',1)") # 字符串拼接sql(禁止使用,会引起sql注入)
inp_1 = ('cdcy',2,)
sql = "insert into tb1(name,part) values('%s','%s')" % inp_1
cursor.execute(sql) # 带参数插入数据(推荐使用)
inp_2 = ('cdcx',2)
cursor.execute("insert into tb1(name,part) values(%s,%s)",inp_2) # 增加多行数据
lis = [('cdc1',2),
('cdc2',2),
('cdc3',2),
]
cursor.executemany("insert into tb1(name,part) values(%s,%s)",lis) # 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
插入数据

删
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
#执行sql操作
r = cursor.execute("delete from tb1 where name=%s",('alex',))
# r为执行sql语句后受影响的行数
print(r)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

改
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
#执行sql操作
r = cursor.execute("update tb1 set name=%s where part=%s",('ccc',1,))
# r为执行sql语句后受影响的行数
print(r)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

查
查新操作时,不需要执行commit操作
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
# 查询数据
cursor.execute('select * from tb3') # 展示一行
result = cursor.fetchone()
print(result)
result = cursor.fetchone()
print(result) # 展示多行
result = cursor.fetchmany(3)
print(result) # 展示全部
result = cursor.fetchall()
print(result)
pymysql查询操作
注意:fetch操作的机制类似于文件操作中的指针,会在上一次的展示基础位置上继续往下展示n行数据
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
# 查询数据
cursor.execute('select * from tb3') # 展示一行
result = cursor.fetchone()
print(result)
result = cursor.fetchone()
print(result) # 展示多行
result = cursor.fetchmany(3)
print(result) # ******************** 执行结果 ***************
"""
(1, 'cdc', 1)
(2, 'ccc', 1)
((3, 'ctt', 3), (4, 'lj', 4), (5, 'xx', 5))
"""
fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(n,mode='relative') # 相对当前位置移动,即从当前位置向前或者向后移动n个位置,再进行数据展示
- cursor.scroll(n,mode='absolute') # 相对绝对位置移动,即从当前位置回到n位置后,再进行数据的展示
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
# 查询数据
cursor.execute('select * from tb3') # 展示一行
result = cursor.fetchone()
print(result)
result = cursor.fetchone()
print(result) # 向前移动一个位置
"""
(1, 'cdc', 1)
(2, 'ccc', 1)
(2, 'ccc', 1)
"""
cursor.scroll(-1,mode='relative') # 向后移动一个位置
"""
(1, 'cdc', 1)
(2, 'ccc', 1)
(4, 'lj', 4) """
cursor.scroll(1,mode='relative')
result = cursor.fetchone()
print(result)
此外,fetch操作默认获取的数据是元祖类型,如果想要或者字典类型的数据,可以通过改变游标的方式实现:
# -*- coding:utf-8 -*-
# author: cdc
# date: 2019/3/18 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询数据
cursor.execute('select * from tb3') # 展示全部
result = cursor.fetchall()
print(result) # ********* 执行结果 ************
"""
[{'part_no': 1, 'name': 'cdc', 'no': 1}, {'part_no': 1, 'name': 'ccc', 'no': 2}, {'part_no': 3, 'name': 'ctt', 'no': 3}, {'part_no': 4, 'name': 'lj', 'no': 4}, {'part_no': 5, 'name': 'xx', 'no': 5}, {'part_no': 9, 'name': 'cc', 'no': 6}, {'part_no': 5, 'name': 'fdc', 'no': 7}]
"""
其他操作
# 注:必须得有自增列 import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='cdc19951216', db='test',charset='utf8')
# 创建游标
cursor = conn.cursor()
# 查询数据
cursor.execute('insert into class(address) values(%s)',('class_3',)) new_id = cursor.lastrowid
print(new_id)
获取最新自增ID
Python学习—数据库篇之pymysql的更多相关文章
- Python学习—数据库篇之SQL补充
一.SQL注入问题 在使用pymysql进行信息查询时,推荐使用传参的方式,禁止使用字符串拼接方式,因为字符串拼接往往会带来sql注入的问题 # -*- coding:utf-8 -*- # auth ...
- Python学习—数据库篇之索引
一.索引简介 索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取即可,对于索引,会保存在额外的文件中.在mys ...
- Python学习—数据库篇之练习题
Mysql测试题 一.表关系 请创建如下表,并创建相关约束 二.操作表 0.在成绩表中同时显示出对应的课程名和学生名 1.自行创建测试数据 2.查询“生物”课程比“物理”课程成绩高的所有学生的学号: ...
- Python学习—数据库篇之SQL语句
一.数据库级别 1.显示数据库 show databases; 默认数据库: mysql - 用户权限相关数据 test - 用于用户测试数据 information_schema - MySQL本身 ...
- Python学习—数据库篇之初识mysql
一.下载与安装 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下公司.MySQL 最流行的关系型数据库管理系统,在 WEB 应用方面MySQL是最好 ...
- Python学习第一篇
好久没有来博客园了,今天开始写自己学习Python和Hadoop的学习笔记吧.今天写第一篇,Python学习,其他的环境部署都不说了,可以参考其他的博客. 今天根据MachineLearning里面的 ...
- [Python学习]错误篇二:切换当前工作目录时出错——FileNotFoundError: [WinError 3] 系统找不到指定的路径
REFERENCE:<Head First Python> ID:我的第二篇[Python学习] BIRTHDAY:2019.7.13 EXPERIENCE_SHARING:解决切换当前工 ...
- [Python学习]错误篇一
REFERENCE:<Head First Python> ID:我的第一篇[Python学习] BIRTHDAY:2019.7.6 EXPERIENCE_SHARING:两个程序错误类型 ...
- python学习 —— python3简单使用pymysql包操作数据库
python3只支持pymysql(cpython >= 2.6 or >= 3.3,mysql >= 4.1),python2支持mysqldb. 两个例子: import pym ...
随机推荐
- 【转】redis实现的分布式锁
参考: 1. https://www.bbsmax.com/A/WpdKpM1zVQ/ 2.https://www.oschina.net/translate/redis-distlock
- 禅知Pro 1.6 前台任意文件读取 | 代码审计
禅知 Pro v1.6 前台任意文件读取 | 代码审计 蝉知专业版是基于蝉知企业门户系统开源版开发,继承了蝉知本身的优秀功能.相对于蝉知开源版增强了商品的属性自定义.属性价格定制.物流跟踪.微信支付. ...
- Activation error occured while trying to get instance of type Database,key ""之Oracle
我在发布web项目时好几次好遇到这个问题,查看了别人的说法,感觉还是不能解决,后来发现在发布时bin里面有dll没有打包到发布文件的bin目录中,而这些dll又是在连接Oracle(我选择的Oracl ...
- centos 6.5 安装redis
1. 下载redis,编译安装 下载地址:https://redis.io/download(建议大家都选择稳定版本) 下载到本地,然后上传到集群 当然也可以通过命令行直接在线下载 $ wget ht ...
- RAMDISK 内存盘工具推荐
好了直接推荐, 1.魔方内存盘 使用方便 ,但是关机后消失.绿色 2.Primo Ramdisk Ultimate Edition5.5 3.GiliSoft RAMDisk 4.QSoft RAM ...
- ELK日志监控平台安装部署简介--Elasticsearch安装部署
最近由于工作需要,需要搭建一个ELK日志监控平台,本次采用Filebeat(采集数据)+Elasticsearch(建立索引)+Kibana(展示)架构,实现日志搜索展示功能. 一.安装环境描述: 1 ...
- 基于bootstrap table配置的二次封装
准备 jQuery js css 引用完毕 开始 如果对bootstrap table 的方法与事件不熟悉: Bootstrap table方法,Bootstrap table事件 <table ...
- 2008R2 部署 aspnetcore repair failed 函数不正确
vc_redist.x64
- leetcode每日刷题计划-简单篇day13
Num 169 先码,回头再说,摩尔算法... tle了 class Solution { public: int majorityElement(vector<int>& num ...
- dax学习
增长率 = (DIVIDE(SUM('业绩达成'[实际业绩]),CALCULATE(SUM('业绩达成'[实际业绩]),PREVIOUSMONTH('业绩达成'[周期])))-1)*100上月业绩 = ...