一、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的更多相关文章

  1. Python学习—数据库篇之SQL补充

    一.SQL注入问题 在使用pymysql进行信息查询时,推荐使用传参的方式,禁止使用字符串拼接方式,因为字符串拼接往往会带来sql注入的问题 # -*- coding:utf-8 -*- # auth ...

  2. Python学习—数据库篇之索引

    一.索引简介 索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取即可,对于索引,会保存在额外的文件中.在mys ...

  3. Python学习—数据库篇之练习题

    Mysql测试题 一.表关系 请创建如下表,并创建相关约束 二.操作表 0.在成绩表中同时显示出对应的课程名和学生名 1.自行创建测试数据 2.查询“生物”课程比“物理”课程成绩高的所有学生的学号: ...

  4. Python学习—数据库篇之SQL语句

    一.数据库级别 1.显示数据库 show databases; 默认数据库: mysql - 用户权限相关数据 test - 用于用户测试数据 information_schema - MySQL本身 ...

  5. Python学习—数据库篇之初识mysql

    一.下载与安装 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下公司.MySQL 最流行的关系型数据库管理系统,在 WEB 应用方面MySQL是最好 ...

  6. Python学习第一篇

    好久没有来博客园了,今天开始写自己学习Python和Hadoop的学习笔记吧.今天写第一篇,Python学习,其他的环境部署都不说了,可以参考其他的博客. 今天根据MachineLearning里面的 ...

  7. [Python学习]错误篇二:切换当前工作目录时出错——FileNotFoundError: [WinError 3] 系统找不到指定的路径

    REFERENCE:<Head First Python> ID:我的第二篇[Python学习] BIRTHDAY:2019.7.13 EXPERIENCE_SHARING:解决切换当前工 ...

  8. [Python学习]错误篇一

    REFERENCE:<Head First Python> ID:我的第一篇[Python学习] BIRTHDAY:2019.7.6 EXPERIENCE_SHARING:两个程序错误类型 ...

  9. python学习 —— python3简单使用pymysql包操作数据库

    python3只支持pymysql(cpython >= 2.6 or >= 3.3,mysql >= 4.1),python2支持mysqldb. 两个例子: import pym ...

随机推荐

  1. 使用java注解实现toJson方法

    如果我有一个对象user,它有几个属性,我想把该对象序列化成一个json字符串,怎么做?我怎么把这种类型的问题实现成一个函数? 注解类似于在被注解的对象上,添加一些简单的属性.在运行时解析这些属性,以 ...

  2. c++ map 注意事项

    1.  往map里面插入元素: 下标方式[]:    map[key] = value; 调用insert:       map.insert(make_pair(key, value)); 下标方式 ...

  3. TCP/IP各层对应的协议

    应用层: 该层包括所有和应用程序协同工作,利用基础网络交换应用程序专用的数据协议.如: HTTP:超文本传输协议. TELNET:(网络电传),通过一个终端(terminal)登录到网络(运行在TCP ...

  4. Spring Cloud Turbine微服务集群实时监控

    本文代码下载地址: https://gitlab.com/mySpringCloud/turbine SpringBoot版本:1.5.9.RELEASE (稳定版) SpringCloud版本:Ed ...

  5. java.util.concurrent包下并发锁的特点与适用场景

    序号 类 备注 核心代码 适用场景 1 synchronized 同步锁 并发锁加在方法级别上,如果是单例class对象,则只能允许一个线程进入public synchronized void doX ...

  6. [转]SQL中的case when then else end用法

      Case具有两种格式.简单Case函数和Case搜索函数. --简单Case函数 CASE sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其他' EN ...

  7. 05-Eclispe配置Tomcat插件

    此插件只针对 eclipse-java-indigo-SR2-win32 这个开发工具使用的 1.下载tomcat插件 2.解压到指定位置 3.找到eclispe安装目录 D:\software\ec ...

  8. new words

    Your cooperation is greatly appreciated 感谢您的合作! budget 预算

  9. 基于vue和svg的树形UI

      vue-svg-tree 基于vue和svg的动态树形UI 截图 应用 npm install vue-svg-tree 示例 <template> <div> <v ...

  10. scrapy-shell, settings

    进入scrapy shell交互终端 scrapy shell  url settings配置文件 NUMBER = 1 可以通过 spider对象调用 class SunshineSpider(sc ...