掌握pymysql 对数据库实现增、删、改、查,数据库工具类封装
注意:由于测试数据库的隐私,一些关键的数据用xx代替。
1. 数据库操作应用场景
1)校验测试数据
比如接口发送请求后明确会对数据库中的某个字段进行修改,但是响应结果中没有该字段数据。 需要借助数据库来校验
2)构造测试数据
有些数据使用一次就失效了,另外是不确定测试数据是否存在。
pymysql操作数据库:
2. 安装
1) pip install PyMySQL
2) pip install PyMySQL -i https://pypi.douban.com/simple
操作步骤:
3. 数据库操作步骤
1)导包 import pymysql
2)创建连接 conn = pymysql.connect(host,port,user,password,database,charset)
3)获取游标 cursor = conn.cursor()
4)执行SQL cursor.execute("sql语句")
- 查询语句 select 处理结果集:(提取数据fetch*)
- 增删改 insert/update/delete
成功:提交事务 conn.commit()
失败:回滚事物 conn.rollback()
5)关闭游标 cursor.close()
6)关闭连接 conn.close()
4. 事务的概念
事务,是关系型数据库特有的概念
事务,可以看作一个虚拟的容器,在容器中存放一系列的数据库操作,看做一个整体。内部的所有操作,要么一次性全部成功,只要有一个失败就全部失败。
5. 连接数据库
conn = pymysql.connect(host="",port="",user="",password="",database="",charset="")
- host: 数据库所在主机的ip地址 -string
- port: 数据库使用的端口号 -int
- user: 连接数据库使用的用户名 -string
- password:连接数据库使用的密码 -string
- database:要链接的数据库的名字 -string
- charset: 字符集。 常用utf8 -string
- conn 连接数据库的对象
入门案例:
由于隐私,一些关键的数据用xx代替。
# 1.导包
import pymysql
# 2.建立连接
conn = pymysql.connect(host="192.168.xx.xx",port=3306,user="xxx",password="xxx",database="xx",charset="utf8")
# 3.获取游标
cursor = conn.cursor()
# 4.执行sql语句
cursor.execute("select * from ab_test_record limit 2")
# 5.获取结果
res = cursor.fetchall()
print("res=",res)
# 6.关闭游标
cursor.close()
# 7.关闭连接
conn.close()
SQL语法回顾:
1)查询语法
select 字段1,字段2,... from 表 where 条件;
示例:SELECT id,username,phone,create_at FROM user where phone="15811262058";
2) 添加语法
insert into 表名(字段1,字段2,...) values(值1,值2,...)
示例:insert into t_book(id,title,pub_date) values(17,'红楼梦','2011-11-11');
3)更新语法
update 表名 set 字段名 = 字段值 where 条件
示例:update t_book set title ='三国' where id = 17;
4)删除语法
delete from 表名 where 条件
示例:delete from t_book where title=‘三国’;
常用方法:
fetchone(): 从结果集中提取一行
fetchmany(size):从结果集中提取size行
fetchall():提取所有结果集
属性rownumber: 可以设置游标位置
案例:
查询t_book表, 获取第一条数据
查询t_book表,获取 前两条 数据
查询t_book表,获取所有数据
查询t_book表,获取第3条和第4条数据
import pymysql
conn = pymysql.connect(host="211.103.xxx.xxx",port=7061,user="student",password="xxxx",database="test_db",charset="utf8")
# 获取游标
cursor = conn.cursor()
# 执行sql语句
cursor.execute("select * from t_book;")
# 提取结果
# res1 = cursor.fetchone()
# res1 = cursor.fetchmany(2)
res1 = cursor.fetchall()
# cursor.rownumber =2
# res1 = cursor.fetchmany(2)
print("res1=",res1)
6. 异常捕获
try:
尝试执行的代码
except Exception as err:
有错误出现时,执行的代码
finally:
无论有没有错误,都会执行的代码
7. 更新(新增/删除/修改)的操作流程
import pymysql
conn = None
cursor = None
try:
conn = pymysql.connect(host="211.103.xxx.xxx",port=7061,user="student",password="xxxx",database="test_db",charset="utf8")
cursor = conn.cursor()
cursor.execute("insert into t_book(id,title,pub_date) values(176,'西游记','1986-1-1');")
print("影响的行数:",conn.affected_rows()) # 影响的行数
conn.commit()
except Exception as e:
print("插入数据错误:",str(e))
conn.rollback()
finally:
cursor.close()
conn.close()
8. 数据库工具类封装
封装的目的:
1)将常用的数据库操作,封装到一个方法。 后续再操作数据库时,通过调用该方法来实现。
2)提交代码的复用性
----设计数据库工具类----
import pymysql
# 封装数据库工具类
class DBUtil(object):
# 添加类属性
conn = None
@classmethod
def __get_conn(cls):
# 判断是否为空, 如果为空再创建
if cls.conn is None:
cls.conn = pymysql.connect(host="211.103.136.244",port=7061,user="student",password="xxx",database="test_db",charset="utf8")
# 返回连接
return cls.conn
@classmethod
def __close_conn(cls):
# 判断如果不为空,则需要关闭
if cls.conn is not None:
cls.conn.close()
cls.conn = None
# 查询一条
@classmethod
def select_one(cls,sql):
cursor = None
res = None
try:
# 获取连接
cls.conn = cls.__get_conn()
# 获取游标
cursor = cls.conn.cursor()
# 执行查询语句
cursor.execute(sql)
# 提取一条结果
res = cursor.fetchone()
except Exception as e:
print("查询错误",str(e))
finally:
# 关闭游标
cursor.close()
# 关闭连接
cls.__close_conn()
return res
# 增删改
@classmethod
def uid_db(cls,sql):
cursor = None
try:
# 获取连接
cls.conn = cls.__get_conn()
# 获取游标
cursor = cls.conn.cursor()
# 执行修改/插入/删除语句
cursor.execute(sql)
print("影响的行数",cls.conn.affected_rows())
# 提交事务
cls.conn.commit()
except Exception as e:
# 回滚事务
cls.conn.rollback()
print("增删改SQL执行失败", str(e))
finally:
# 关闭游标
cursor.close()
# 关闭连接
cls.__close_conn()
if __name__ == "__main__":
res = DBUtil.select_one("select * from t_book;")
print("查询结果为:",res)
DBUtil.uid_db("update t_book set is_delete = 1 where id =5;")