Python interface test combat 3 (upper) - operation of the database Python

This Section

  • Database operations
  • Package database operations

Foreword

In the function, interface testing is often required by the operation of the database, to prepare data, testing and verification environment features, database operation interface is correct.
In automated testing, we need to use the code automatically connect to the database data preparation, and environmental inspection database assertion function.
MySQL database operations using Python here we need to use the tripartite libraryPyMySQl

installation method:pip install pymysql

Database operations

  1. Establish a database connection conn = pymysql.connect()
  2. Cursor from the connection establishing operation cur = conn.cursor()
  3. Use a cursor to perform sql (read / write) cur.execute(sql)
  4. Getting Results (read) / submit the changes (write) cur.fetchall()/conn.commit()
  5. Close the cursor and connection cur.close();conn.close()
import pymysql

# 1. 建立连接
conn = pymysql.connect(host='127.0.0.1',
                    port=3306,
                    user='root', passwd='123456', # password也可以 db='api_test', charset='utf8') # 如果查询有中文需要指定数据库编码 # 2. 从连接建立游标(有了游标才能操作数据库) cur = conn.cursor() # 3. 查询数据库(读) cur.execute("select * from user where name='张三'") # 4. 获取查询结果 result = cur.fetchall() print(result) # 3. 更改数据库(写) cur.execute("delete from user where name='李四'") # 4. 提交更改 conn.commit() # 注意是用的conn不是cur # 5. 关闭游标及连接 cur.close() conn.close() 

What are cursors? Similarly cursor file handle, you can access the database by one of the results set. pymysql can only be executed sql and get results through a cursor

Query
using cur.execute (), after executing a database query returns the number of rows no influence, rather than results. We want to use cur.fetchone()/cur.fetchmany()/cur.fetchall()to get results

  • cur.fetchone (): Gets a data (simultaneously acquired data will be deleted from the result set), return Ganso('张三','123456')
  • cur.fetchmany (3): obtaining a plurality of data, nesting ancestral(('张三','123456'),('李四','123456'),("王五","123456"))
  • cur.fetchall (): Get all the data, nesting tuples, (('张三','123456'),)(only one data)

Note: After obtaining the data, the data will be deleted from the centralized data acquisition once again get less, such as:

cur.execute(select * from user where name='张三')
print(cur.fetchone()) # 结果: ('张三','123456')
print(cur.fetchone()) # 结果:None print(cur.fetchall()) # 结果:() 

So we need to re-use query results, query results need to be assigned to a variable

cur.execute(select * from user where name='张三')
result = cur.fetchall()
print(result)  # 结果: ('张三','123456')
print(result) # 结果: ('张三','123456') 

Modify the operation
does not take effect immediately after the operation performed modify the database using the connection conn.commit()take effect until commit and rollback support things

try:
    cur.execute("insert into user (name,password) values ('张三', '123456')")
    cur.execute("insert into user (name, passwd) values ('李四'), '123456'") # 此处sql出错
    conn.commit()  # 使用连接提交所有更改 except Exception as e: conn.rollback() # 回滚所有更改(注意用的是conn) print(str(e)) 

Package database operations

Since often use to the database, it is recommended that all database operations packaged into a common database module

  1. New db.py, code as follows:
import pymysql


# 获取连接方法
import pymysql


# 获取连接方法
def get_db_conn(): conn = pymysql.connect(host='127.0.0.1', port=3306, user='test', passwd='123456', db='api_test', charset='utf8') # 如果查询有中文,需要指定测试集编码 return conn # 封装数据库查询操作 def query_db(sql): conn = get_db_conn() # 获取连接 cur = conn.cursor() # 建立游标 cur.execute(sql) # 执行sql result = cur.fetchall() # 获取所有查询结果 cur.close() # 关闭游标 conn.close() # 关闭连接 return result # 返回结果 # 封装更改数据库操作 def change_db(sql): conn = get_db_conn() # 获取连接 cur = conn.cursor() # 建立游标 try: cur.execute(sql) # 执行sql conn.commit() # 提交更改 except Exception as e: conn.rollback() # 回滚 finally: cur.close() # 关闭游标 conn.close() # 关闭连接 # 封装常用数据库操作 def check_user(name): # 注意sql中''号嵌套的问题 sql = "select * from user where name = '{}'".format(name) result = query_db(sql) return True if result else False def add_user(name, password): sql = "insert into user (name, passwd) values ('{}','{}')".format(name, password) change_db(sql) def del_user(name): sql = "delete from user where name='{}'".format(name) change_db(sql) 

Compared with the embodiment sql directly manipulate the database, the package common database operations safer

  1. Call the method (other modules)
from db import *

if check_user("张三"):
    del_user("张三") 

NOTE: Another packaging method

Since this packaging method above, each database query will establish a connection, less efficient, can also be employed below the object-oriented method of packaging

db2.py

import pymysql


class DB:
    def __init__(self): self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', # passwd 不是 password db='api_test') self.cur = self.conn.cursor() def __del__(self): # 析构函数,实例删除时触发 self.cur.close() self.conn.close() def query(self, sql): self.cur.execute(sql) return self.cur.fetchall() def exec(self, sql): try: self.cur.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print(str(e)) def check_user(self,name): result = self.query("select * from user where name='{}'".format(name)) return True if result else False def del_user(self, name) self.exec("delete from user where name='{}'".format(name)) 

Instructions

from db2 import DB:

db = DB()  # 实例化一个数据库操作对象
if db.check_user("张三"): db.del_user("张三") 

After words

  • Database connection information configuration file written recommendations, read from the configuration file
  • sql statement recommended to look no further Grammar packaged in manual testing
  • Various operations can be accomplished by encapsulating various service sql
  • Change the database at risk, operations need to be cautious! ! !



Guess you like

Origin www.cnblogs.com/gdg87813/p/11225535.html