python连接数据库校验使用pymysql库unittest+requests库使用
pymysql实现连接数据库步骤
代码demo:
import pymysql
# 创建连接(可指定对应数据库名)
conn = pymysql.connect(host='localhost', user='root', password='1996')
# 创建游标对象
cursor = conn.cursor()
# 执行sql
cursor.execute("select version()")
# 获取查询结果
re = cursor.fetchall()
print(re)
# 释放对象
cursor.close()
conn.close()
常用查询方法
fetchone():获取下一个查询集,结果集是一个对象fetchall():获取全部返回集结果rowcount:执行sql后影响的记录行数
数据库事务处理
场景:用于对一系列操作要么同时成功或者同时失败,不能只是其中一部分操作成功
事务提交机制
自动提交
conn.autocommit(False): 设置是否开启自动提交事务,默认不开启
手动提交
conn.commit(): 提交事务
回滚事务
conn.rollback()
例:插入记录
import pymysql
try:
# 创建连接
conn = pymysql.connect(host='localhost', user='root',
password='1996', database='work', autocommit=False)
# 创建游标对象
cursor = conn.cursor()
# 执行sql
cursor.execute("insert into emp(no,name,sal,dpmp) values(106,'奥特曼',90.0,4)")
# 手动提交
conn.commit()
except Exception as e:
print("出错回滚")
conn.rollback()
finally:
# 释放对象
if cursor:
cursor.close()
if conn:
conn.close()
封装数据库操作工具类
import pymysql
# 数据库连接工具类
class DBUtil:
_conn = None
# 获取连接
@classmethod
def get_conn(cls):
if cls._conn is None:
cls._conn = pymysql.connect(host='localhost', user='root', password='1996', database='work',autocommit=False)
return cls._conn
# 关闭连接
@classmethod
def close_conn(cls):
if cls._conn:
cls._conn.close()
# 获取游标对象
@classmethod
def get_cursor(cls):
return cls.get_conn().cursor()
# 释放游标
@classmethod
def close_cursor(cls, cursor):
if cursor:
cursor.close()
# 业务操作
@classmethod
def get_record(cls, sql):
record_data = None
cursor = None
try:
cursor = cls.get_cursor()
cursor.execute(sql)
record_data = cursor.fetchall()
except Exception as e:
print("出错回滚")
cls.get_conn().rollback()
finally:
cls.get_cursor().close()
cls.get_conn().close()
return record_data
Unittest+Requests库使用接口测试
安装request库,pip install requests常用请求方法:get,post,delete,put
基本用法:
import requests
# Get请求
response = requests.get("http://www.baidu.com")
print(response.cookies, response.text, response.headers)
# Post请求,data填写发送到请求体中的表单数据,json填写json格式数据发送到请求体
data = {"username": "13800138009", "verify_code": "8888", "password": "1996", "password": "1996"}
response = requests.post("http://tpshop-test.itheima.net/Home/User/reg.html", json=data)
print(response.status_code)
print(response.text)
response = requests.get("http://www.weather.com.cn/data/sk/101010100.html")
print(response.json())
cookie
# 键值对 cookies = response.cookies
Session
import requests
# 创建会话,通过会话对象进行请求
session = requests.Session()
# 获取验证码
response = session.get("http://localhost/index.php?m=Home&c=User&a=verify")
# 登录
login_data = {"username": "13012345678", "password": "123456", "verify_code": "8888"}
response = session.post("http://localhost/index.php?m=Home&c=User&a=do_login", data=login_data)
# 我的订单
response = session.get("http://localhost/Home/Order/order_list.html")
print(response.text)
session.close()
测试框架
项目基础目录:
代码:lc/ihrmframework_requests_unittest



