robot framework自动化框架——mysql

看了半天DatabaseLibrary,差不多理解了,我现在就是打算自己把他拿过来为己所用,读书人的事,是窃是窃。去除了和robot有关的方法,并去除了数据库选择,直接只用mysql,一般也是用mysql吧。

import sys
import pymysql


class Query(object):
    def query(self, selectStatement, sansTran=False, returnAsDict=False):
        """
        :param selectStatement: 查询语句
        :param sansTran:True进行回滚操作,正常别去管这个入参即可(个人理解,仅供参考,错漏之处欢迎指出:就是把用户当傻子的想法,万一你给的不是select给了一个delete或者给了一个drop咋整。。。当然你觉得自己不是傻子就别管,对不对,谁告诉我标准答案了)
        :param returnAsDict:默认False,不设置返回的就是元组,设置为True返回的就是字典
        :return:mysql查询结果
        """
        cur = None
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Query  |  %s ' % selectStatement)
            self.__execute_sql(cur, selectStatement)
            allRows = cur.fetchall()

            if returnAsDict:
                mappedRows = []
                col_names = [c[0] for c in cur.description]

                for rowIdx in range(len(allRows)):
                    d = {}
                    for colIdx in range(len(allRows[rowIdx])):
                        d[col_names[colIdx]] = allRows[rowIdx][colIdx]
                    mappedRows.append(d)
                return mappedRows

            return allRows
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def row_count(self, selectStatement, sansTran=False):
        """
        :param selectStatement: 查询语句
        :param sansTran: 回滚标识
        :return: 返回查询的行数统计
        """
        cur = None
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Row Count  |  %s ' % selectStatement)
            self.__execute_sql(cur, selectStatement)
            rowCount = cur.rowcount
            return rowCount
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def description(self, selectStatement, sansTran=False):
        """
        :param selectStatement: 查询语句
        :param sansTran: 回滚标识
        :return: 返回表的属性
        """
        cur = None
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Description  |  %s ' % selectStatement)
            self.__execute_sql(cur, selectStatement)
            description = list(cur.description)
            if sys.version_info[0] < 3:
                for row in range(0, len(description)):
                    description[row] = (description[row][0].encode('utf-8'),) + description[row][1:]
            return description
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def delete_all_rows_from_table(self, tableName, sansTran=False):
        """
        :param tableName:需求清空表的表名
        :param sansTran: 回滚标识
        :return: 无返回
        """
        cur = None
        selectStatement = ("DELETE FROM %s;" % tableName)
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Delete All Rows From Table  |  %s ' % selectStatement)
            result = self.__execute_sql(cur, selectStatement)
            if result is not None:
                if not sansTran:
                    self._dbconnection.commit()
                return result
            if not sansTran:
                self._dbconnection.commit()
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def execute_sql_script(self, sqlScriptFileName, sansTran=False):
        """
        :param sqlScriptFileName: sql脚本文件名
        :param sansTran: 回滚标识
        :return: 无返回
        """
        sqlScriptFile = open(sqlScriptFileName)

        cur = None
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Execute SQL Script  |  %s ' % sqlScriptFileName)
            sqlStatement = ''
            for line in sqlScriptFile:
                PY3K = sys.version_info >= (3, 0)
                if not PY3K:
                    # spName = spName.encode('ascii', 'ignore')
                    line = line.strip().decode("utf-8")
                if line.startswith('#'):
                    continue
                elif line.startswith('--'):
                    continue

                sqlFragments = line.split(';')
                if len(sqlFragments) == 1:
                    sqlStatement += line + ' '
                else:
                    for sqlFragment in sqlFragments:
                        sqlFragment = sqlFragment.strip()
                        if len(sqlFragment) == 0:
                            continue

                        sqlStatement += sqlFragment + ' '

                        self.__execute_sql(cur, sqlStatement)
                        sqlStatement = ''

            sqlStatement = sqlStatement.strip()
            if len(sqlStatement) != 0:
                self.__execute_sql(cur, sqlStatement)

            if not sansTran:
                self._dbconnection.commit()
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def execute_sql_string(self, sqlString, sansTran=False):
        '''
        :param sqlString: 增删改语句的执行,通过字符串格式输入
        :param sansTran: 回滚标识
        :return: 无返回
        '''
        cur = None
        try:
            cur = self._dbconnection.cursor()
            print('Executing : Execute SQL String  |  %s ' % sqlString)
            self.__execute_sql(cur, sqlString)
            if not sansTran:
                self._dbconnection.commit()
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def call_stored_procedure(self, spName, spParams=None, sansTran=False):
        '''
            这个方法忽略吧,是存储过程,作为测试人员,用不到的
        '''
        if spParams is None:
            spParams = []
        cur = None
        try:
            cur = self._dbconnection.cursor(as_dict=False)
            PY3K = sys.version_info >= (3, 0)
            if not PY3K:
                spName = spName.encode('ascii', 'ignore')
            print('Executing : Call Stored Procedure  |  %s  |  %s ' % (spName, spParams))
            cur.callproc(spName, spParams)
            cur.nextset()
            retVal = list()
            for row in cur:
                retVal.append(row)
            if not sansTran:
                self._dbconnection.commit()
            return retVal
        finally:
            if cur:
                if not sansTran:
                    self._dbconnection.rollback()

    def __execute_sql(self, cur, sqlStatement):
        return cur.execute(sqlStatement)

    def __init__(self, host=None, port=None, user=None, password=None, database=None, charset=None):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset
        self._dbconnection = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                             database=self.database,
                                             charset=self.charset)

复制粘贴就可以用,已亲测。

from example import DatabaseLibrary

query = DatabaseLibrary.Query(host='***.***.***.***',
                              port=3306,
                              user='*********',
                              password='***********',
                              database='nf_mcht_basic',
                              charset='utf8')
dict = query.query("SELECT t.`company_name` FROM `tbl_card` t WHERE t.`card_no`=1536464484589696;", sansTran=False,
                   returnAsDict=False)
print(dict)
rowsnumber = query.row_count(
    "SELECT t.`company_name` FROM `tbl_card` t WHERE t.`card_no` in (1536464484589696,1536549965694016);")
print(rowsnumber)

description = query.description("SELECT * FROM `tbl_card`")
print(description)

突然想起,有个小知识点忘了提了,就是python可以直接判断变量,None就是False

c = None
if c:
    print("直接判断变量")
else:
    print("else")

 

 

 

 

 

print_r('点个赞吧');
var_dump('点个赞吧');
NSLog(@"点个赞吧!")
System.out.println("点个赞吧!");
console.log("点个赞吧!");
print("点个赞吧!");
printf("点个赞吧!\n");
cout << "点个赞吧!" << endl;
Console.WriteLine("点个赞吧!");
fmt.Println("点个赞吧!")
Response.Write("点个赞吧");
alert(’点个赞吧’)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值