#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File     : database_oracle
# @Author   : LiuYan
# @Time     : 2021/10/13 16:10

import os
import cx_Oracle

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


class DatabaseOracle(object):
    def __init__(self, database_config: dict):
        super(DatabaseOracle, self).__init__()
        self._conn = None
        self._cursor = None
        self._database_config = database_config
        self._connect()

    def _connect(self) -> None:
        self._conn = cx_Oracle.connect(
            self._database_config['user'],
            self._database_config['password'],
            self._database_config['host'] + ':' + str(self._database_config['port']) + '/' + self._database_config['database']
        )
        self._cursor = self._conn.cursor()

    def query(self, sql: str) -> list:
        # 获取表单信息
        print('SQL: {}'.format(sql))
        self._cursor.execute(sql)
        list_result = self.rows_as_dicts()
        return list_result

    def rows_as_dicts(self) -> list:
        """
        将查询结果转为dict
        :return:
        """
        col_names = [i[0] for i in self._cursor.description]
        return [dict(zip(col_names, row)) for row in self._cursor]

    def close(self) -> None:
        self._cursor.close()
        self._conn.close()


if __name__ == '__main__':
    database_config = {
        'host': '114.116.91.1',
        'port': 1521,
        'user': 'cis',
        'password': 'cis_zzsn9988',
        'database': 'ORCL'
    }
    dbo = DatabaseOracle(database_config=database_config)

    sql = '''
    select 
        TITLE as 标题,
        SUMMARY as 摘要,
        ORIGIN as 来源
    from CIS_ANS_BASEDATA where ROWNUM < 10'''
    list_result = dbo.query(sql=sql)
    print(list_result)
    dbo.close()
