前言

最近有导出大批量Oracle数据的需求,用PL/SQL查询并导出EXCEL的耗时较长,且占用内存较大。尝试改用Python,提高了效率,节省了内存空间。


一、cx_Oracle是什么?

cx_Oracle 是由甲骨文公司提供支持的开源的Python模块,提供了访问Oracle数据库的API。

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

二、安装步骤

1.安装Oracle Client

使用cx_Oracle之前要确保本机存在Oracle客户端并正确配置,可以直接去官网下载较新的版本:
Oracle Client
配置TNS_ADMIN环境变量:TNS_ADMIN.ora 文件的位置
该文件放置在Oracle Client根目录下
在这里插入图片描述
在这里插入图片描述

2.配置cx_Oracle:

pip install cx_Oracle -i https://pypi.tuna.tsinghua.edu.cn/simple

该处使用的是临时切换国内镜像源,也可以配置镜像源后再安装。

3.配置DLL文件:


将Oracle Client Instant 目录下 *.dll 拷贝至Python安装根目录下(Python版本要求3.6以上)
(更正:关键是DLL文件,Python目录下必须有,其他不重要)

二、使用

1.基本用法

import cx_Oracle


def main():
	# 建立连接
	db = cs_Oracle.connect('username', 'password', 'url/servername:port')
	# 获取游标
	cursor = db.cursor()
	# 查询数据
	cursor.execute('SELECT * FROM t_temp')
	# 获取数据
	data = cursor.fetchall()
	print(data)
	# 获取字段名
	title = cursor.description
	print(title)

2.条件查询

def temp(cursor, age, sex):
	# 查询大于一定年龄的某性别老师
	sql = """
	SELECT * FROM teacher WHERE age >= :age AND sex = :sex
	"""
	cursor.execute(str=sql, age=age, sex=sex)
	data = cursor.fetchall()
    title = cursor.description
    result = {
        'title': title,
        'data': data,
    }
    print(result)

3.导出数据到Excel文件

使用openpyxl库将查到的数据转为Excel(.xlsx格式),并试着用自定义的Excel类将生成Excel的步骤封装,这样只要给固定的数据格式,就不用关心Excel的具体生成了。

import logging

from openpyxl import Workbook, load_workbook
from openpyxl.styles import *


class Excel:
    """
    @description : 
    @Author : admin 
    @Time : 2022-04-08 15:37 
    """

    def __init__(self):
    	# 标题A1、B1、...
        self.character_list = [
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'G',
            'H',
            'I',
            'J',
            'K',
            'L',
            'M',
            'N',
            'O',
            'P',
            'Q',
            'R',
            'S',
            'T',
            'U',
            'V',
            'W',
            'X',
            'Y',
            'Z',
        ]
        self.column_list = [
            [item for item in self.character_list],
            ['A' + item for item in self.character_list],
            ['B' + item for item in self.character_list],
        ]

    def run(self, result, full_file_name):
        """
        @description : 
        @Author : admin 
        @Time : 2022-04-08 15:37 
        """
        # 生成表格字段标题
        row = 1
        try:
            wb1 = load_workbook(full_file_name)
            ws1 = wb1['数据']
        except Exception as e:
            logging.warning(e)
            wb1 = Workbook()
            ws1 = wb1['Sheet']
            ws1.title = '数据'
        index = 0
        for item in result['title']:
            i = int(index / 26)
            j = index % 26
            cell_pos = self.column_list[i][j] + str(row)
            ws1[cell_pos] = item[0]
            # 字体
            ws1[cell_pos].font = Font(bold=True)
            # 列宽
            ws1.column_dimensions[self.column_list[i][j]].width = 15
            index += 1
        row += 1
        # 插入数据
        for data_list in result['data']:
            index = 0
            for item in data_list:
                i = int(index / 26)
                j = index % 26
                ws1[self.column_list[i][j] + str(row)] = item
                index += 1
            row += 1
        # 保存数据
        wb1.save(full_file_name)

注: run()中result数据格式为=> “2.条件查询” 中格式

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐