首页 > 技术文章 > python之操作数据库

testling 2019-11-14 18:16 原文

进行接口测试的时候,为了保证自动化测试用例可持续性,那么就会对数据库进行增删改查等操作。

首先来写公共函数;操作数据库的四个方法:

# coding=utf-8
import MySQLdb


class MySql():
def __init__(self, db, host="数据库Ip", port=3306, user="数据库用户名", password="数据库密码"):
self.mysql = MySQLdb.Connect(
host=host,
port=port,
user=user,
passwd=password,
db=db,
charset="utf8")

self.cursor = self.mysql.cursor()

def query(self, sql):
# type: (object) -> object
"""
查询
:param sql:
:return:
"""
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result

def update(self, sql):
"""
修改
:param sql:
:return:
"""
self.cursor.execute(sql)
self.mysql.commit()

def delete(self, sql):
"""
删除
:param sql:
:return:
"""

self.cursor.execute(sql)
self.mysql.commit()

def insert(self, sql):
"""
插入
:param sql:
:return:
"""
self.cursor.execute(sql)
self.mysql.commit()
return "success"
def close(self):
self.mysql.close()


if __name__ == "__main__":
#进行插入数据:(当数据太多可以进行先读文件,读取到的数据来进行插入)
# MySql = MySql("signupservice")
# data=open('./test','r')
# sql=data.read()
# MySql.insert(sql=sql)
# MySql.close()


MySql = MySql("signupservice")
print MySql.query(sql='SELECT * from common_otp where mobile=9421510000')
MySql.close()

推荐阅读