python接口自动化测试框架实现之操作oracle数据库

python操作oracle数据库需要使用到cx-oracle库。

安装:pip install cx-oracle

python连接oracle数据库分以下步骤:

1、与oracle建立连接;

2、获取游标;

3、执行sql语句;

4、fetch查询结果或commit修改结果;

5、关闭游标;

6、关闭oracle连接。

 

完整示例如下:

 

# -*- coding:utf-8 -*-

import cx_Oracle as oracle
from readConfig import get_config_values
from utils.resutltodict import dict_fetchall


def execute_oracle_sql_query(sql, params):
    """
    执行oracle sql查询语句
    :param sql: sql语句,变量使用 :var或者:1,:2表示
    :param params: 变量值,传入元祖
    :return: queryset
    """
    dsn_tns = oracle.makedsn(get_config_values('oracle', 'host'), get_config_values('oracle', 'port'),
                             get_config_values('oracle', 'sid'))
    print(dsn_tns)
    conn = oracle.connect(user=get_config_values('oracle', 'user'), password=get_config_values('oracle', 'password'),
                          dsn=dsn_tns)
    cursor = conn.cursor()
    cursor.execute(sql, params)
    qryset = dict_fetchall(cursor)
    cursor.close()
    conn.close()
    return qryset

if __name__ == '__main__':
    sql = """select t.*,rowid from ch_info_dictitem t where t.groupid=:1"""
    params = ('WorkFlowCategory', )
    print(execute_oracle_sql_query(sql=sql, params=params))

cx_oracle的详细使用见官文:

 

https://oracle.github.io/python-cx_Oracle/

 

posted @ 2018-03-13 14:39  ianduin  阅读(1439)  评论(0编辑  收藏  举报