02-09 Python library-PyMySQL-connect to the database

机智的测试生活
中文

Scenarios that need to connect to the database

  1. For example, the registration interface, the same account cannot be registered repeatedly
  2. For example, the process interface: login-bind bank card-unbind bank card When testing to unbind a bank card, you need to create a data to bind the bank card first
  3. Modify the state of the interface, for example, an interface has several states: bound-in use-cancelled. When testing the different states of the interface, the data needs to be restored
  4. Data cleaning, the test is completed to clean up junk data

Install

pip install PyMySQL 

Connect to the database

import pymysql

# 数据库信息
db_info = {
    "host": "127.0.0.1",  # ip
    "user": "root",  # 用户名
    "password": "123456",  # 密码
    "port": 3306}  # 端口


class DbConnect():
    def __init__(self, db_cof, database=""):
        self.db_cof = db_cof
        # 打开数据库连接
        self.db = pymysql.connect(database=database,
                                  cursorclass=pymysql.cursors.DictCursor,
                                  **db_cof)

        # 使用cursor()方法获取操作游标
        self.cursor = self.db.cursor()

    def select(self, sql):
        # SQL 查询语句
        # sql = "SELECT * FROM EMPLOYEE \
        #        WHERE INCOME > %s" % (1000)
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        return results

    def execute(self, sql):
        # SQL 删除、提交、修改语句
        # sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
        try:
           # 执行SQL语句
           self.cursor.execute(sql)
           # 提交修改
           self.db.commit()
        except:
           # 发生错误时回滚
           self.db.rollback()

        def close(self):
            # 关闭连接
            self.db.close()


def select_sql(select_sql):
    '''查询数据库'''
    db = DbConnect(dbinfo, database="apps")
    result = db.select(select_sql)  # 查询
    db.close()
    return result

def execute_sql(insert_sql):
    '''执行sql'''
    db = DbConnect(dbinfo, database="apps")
    db.execute(insert_sql)  # 查询
    db.close()
阅读 1.1k

机智的测试生活
双非大龄青年,转行测试工程师。 分享测试工程师的职业经验, 提供付费转行咨询

公号|机智的测试生活

80 声望
477 粉丝
0 条评论

公号|机智的测试生活

80 声望
477 粉丝
文章目录
宣传栏