robotframework访问mysql数据库--DatabaseLibrary 库(9)

一、以SSH通道方式远程连接数据库

预备条件:python 3.X 安装PyMySQL、sshtunnel模块(pip install PyMySQL、pip install sshtunnel)

  • PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。
  • sshtunnel用于远程连接数据库,以SSH通道方式。
#该connection_mysql.py文件,用于远程连接数据库
import pymysql
import os,sys
from sshtunnel import SSHTunnelForwarder
 
def mysql_test(sql): 
    with SSHTunnelForwarder(    #ssh的地址,端口,用户名,密码
            ('1……4', 22022),
            ssh_password="……", #这是密码哦,不是账号
            ssh_username="……e",
            remote_bind_address=('192……',3306)) as server:         
        conn = pymysql.connect(host='127.0.0.1', #此处必须是是127.0.0.1
                               port=server.local_bind_port,
                               user='root',    #数据库用户名和密码
                               passwd='1……',
                               db='c……l')#以及数据库名称
        cursor = conn.cursor()    #.cursor()用来获得python执行Mysql命令的方法
        select = sql
        cursor.execute(select)    #.execute()执行mysql语句       
        data=cursor.fetchall()    #fetchall()则是接收全部的返回结果行
    return data    

 
if __name__ == "__main__":
     sql='SELECT * FROM sys_play_logs ORDER BY id LIMIT 10;';
     #print(mysql_test(sql));

安装DatabaseLibrary库

安装:pip install robotframework-databaselibrary

导入DatabaseLibrary库

导入connection_mysql.py文件

创建测试套件-测试用例:

并使用定义的方法,查询10条记录:

二、直接访问本地数据库

用到DatabaseLibrary数据库中的connection to关键字

-----------------------------------------Have a good day!---------------------------------------------------------------------------------------------------
原文地址:https://www.cnblogs.com/ww-xiaowei/p/10414262.html