Python-based interface automation - pymysql module to operate database

Table of contents

introduction

1. PyMySQL installation

2. Python operates the database

write at the end


introduction

        When performing functional or interface testing, it is often necessary to connect to the database, operate and view relevant data table data, and use it to build test data, check functions, verify data consistency, and whether the database operation of the interface is correct, etc.

Therefore, when performing interface automation testing, we also cannot avoid the interaction between the interface and the database. We need to use code to connect to the database, and complete data preparation, environment inspection, and database assertion functions by operating the database.

In python3, using python to operate MySQL database requires the use of a third-party library: pymysql, which is essentially a socket client software package, which provides a series of methods for connecting to databases and operating database tables.

1. PyMySQL installation

1. Install in windows environment

Since python3.6 and above versions come with pip3 after installing python, if the python version is lower than 3.6, you can manually install pip, so you can directly use pip to install the module

pip3 install pymysql

2. Install in linux environment

Download and install the tar package of pymysql. After decompression, enter the decompression directory and install it as follows:

[root@localhost opt]#tar -xzvf PyMySQL-0.7.11.tar.gz
[root@localhost opt]#cd PyMySQL-0.7.11
[root@localhost PyMySQL-0.7.11]#python36 setup.py install

3. Install in PyCharm

Retrieve the module directly in PyCharm and install it, the steps are as follows:

2. Python operates the database

For the convenience of testing, we first create a test table in the mysql database: userinfo, the table information is as follows:

 

After having the database and data table, we can import the pymysql module and use the method encapsulated under the module to realize the database operation

Database Connectivity

The methods provided by pymysql are as follows:

1. Establish a database connection conn = pymysql.connect()
2. Establish an operation cursor from the connection cur = conn.cursor()
3. Use the cursor to execute sql (read/write) cur.execute(sql)
4. Get the result (read) / Commit changes (write) cur.fetchall() / conn.commit()
5. Close the cursor and connection cur.close();conn.close()

Code example:

import pymysql
# 建立连接
connection = pymysql.connect(host='119.29.78.234', port=3306, user='root', password='dhcc@2020', db='test123')
cursor = connection.cursor()       # 创建游标
cursor.execute("SELECT * FROM userinfo")   #使用execute()方法执行SQL语句
data = cursor.fetchall()  #使用fetall()获取全部数据
print(data)
cursor.close()   #关闭游标和数据库的连接
connection.close()<br><br>#运行结果<br>((1, '艾佛森', '123'), (2, '科比', '123'), (3, '詹姆斯', '123'), (4, '库里', '123'))

What is a cursor? A cursor is similar to a file handle, and can access the database execution result set one by one. In pymysql, only cursors can be used to execute sql and obtain results

After the above code is executed, a nested tuple data type is returned by default

Database CRUD

 Query operation:

With cur.execute(), what is returned after executing a database query is the number of affected rows, not the query result. We need to use cur.fetchone()/cur.fetchmany()/cur.fetchall() to get the query result
cur.fetchone(): Get a piece of data (at the same time, the data will be deleted from the result set), and return the tuple
cur. fetchmany(3): Fetch multiple pieces of data, return a nested tuple
cur.fetchall(): Fetch all data, return a nested tuple

Code example:

Query a single piece of data:

import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchone()    # fetchone()第一次只能查询表中的首行数据
print(res)
res = cursor.fetchone()    # 第二次查询下一行数据
print(res)
cursor.close()
db.close()<br><br># 返回结果

((1, 'Iverson', '123'))

((2, 'Kobe', '123'))

Query multiple pieces of data:

import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchmany(3)   # 第一次查询表中的前3行数据
print(res)
res = cursor.fetchmany(3)    # 第二次查询下一个3行的数据
print(res)
cursor.close()
db.close()<br>
#返回结果
((1, '艾佛森', '123'), (2, '科比', '123'), (3, '詹姆斯', '123'))
((4, '库里', '123'),)

Query all data:

import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchall()   # 第一次查询表中的所有数据
print(res)
res = cursor.fetchall()    # 第二次查询无数据
print(res)
cursor.close()
db.close()<br>
#返回结果
((1, '艾佛森', '123'), (2, '科比', '123'), (3, '詹姆斯', '123'), (4, '库里', '123'))
()

 The default is to return the data type of tuple, which seems unintuitive. Therefore, the cursor can be set as follows when instantiating, and the data of dictionary type can be returned

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)<br><br>#返回结果

[{'username': 'Iverson', 'id': 1, 'passwd': '123'}, {'username': 'Kobe', 'id': 2, 'passwd': '123'} , {'username': 'James', 'id': 3, 'passwd': '123'}, {'username': 'Curry', 'id': 4, 'passwd': '123'}]

Addition, deletion and modification operations:

Additions, deletions, and database modifications do not take effect immediately. They take effect only after they are submitted using the connection conn.commit(). Things and rollback are supported.

 Code example:

import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES('克莱','123')"
#sql = "UPDATE userinfo SET username = '奥尼尔' WHERE username = '科比'"  # 修改数据
#sql = "DELETE FROM username WHERE username ='奥尼尔'"                    # 删除数据
try:
    cursor.execute(sql)
    db.commit()
except Exception as e :   # 执行异常回滚
    db.rollback()
cursor.close()
db.close()
#或者在execute提供需要插入的数据
import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
try:
    cursor.execute(sql,("克莱","123"))
    db.commit()
except Exception as e :
    db.rollback()
cursor.close()
db.close()
#批量插入数据
import pymysql
db_config = {
      "host":"119.29.78.234",
       "port":3306,
       "user":"root",
       "password":"dhcc@2020",
       "db":"test123"
}
db = pymysql.connect(**db_config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
try:
    cursor.executemany(sql,[("韦德","123"),("字母哥","123")])
    db.commit()
except Exception as e :
    db.rollback()
cursor.close()
db.close()

Encapsulate database operations

Since database operations are often used, it is recommended to encapsulate all database operations into a common database module

The encapsulated code example is as follows:

import pymysql.cursors
 
class Operation_mysql(object):
    def __init__(self):
        # 建立连接
        db_config = {
            "host": "119.29.78.234",
            "port": 3306,
            "user": "root",
            "password": "dhcc@2020",
            "db": "test123"
        }
        self.connection = pymysql.connect(**db_config)
        # 创建游标
        self.cursor = self.connection.cursor()
 
    def execute_sql(self, sql):
        try:
            self.cursor.execute(sql)
            self.connection.commit()
        except Exception as e:  # 执行异常回滚
            db.rollback()
 
    def get_data(self):
        data = self.cursor.fetchone()
        #data = self.cursor.fetchall() # 查询所有数据
        return data
 
    def close_mysql(self):
        # 关闭游标
        self.cursor.close()
        # 关闭数据库连接
        self.connection.close()

In this way, when subsequent interface test cases need to operate the database after encapsulation, the module can be introduced, and the instantiated object calls the method under the module.

write at the end

This post ends here, and finally, I hope that friends who read this post can gain something.

It's all here, remember to support Sanlian.

-------------------------------------------------

How to download the full version of the document:

These materials should be the most comprehensive and complete preparation warehouse for friends who are engaged in [software testing]. This warehouse has also accompanied me through the most difficult journey, and I hope it can help you too! All of the above can be shared.

Interact with me in the comment area or privately ❤ me [Software Testing and Learning] to get it, no thanks for taking it away.

 

おすすめ

転載: blog.csdn.net/weixin_67553250/article/details/131070185