프린트 하기

OS 환경 : Oracle Linux 7.6 (64bit)

 

SW 환경 : VS Code 1.87.2, Python 3.12.2

 

DB 환경 : Oracle Database 19.3.0.0

 

방법 : 오라클 19c 파이썬을 이용해 여러개 DB 데이터 조회 후 엑셀 파일로 저장(pandas)

파이썬환경에서 오라클에 접속해서 데이터를 가져온 뒤 엑셀로 저장하는 방법을 설명함
이 방법을 사용하기 위해 pandas 모듈을 이용함

 

 

사전 설정 :
- VS Code 다운로드 : Windows 10에 Visual Studio Code 설치 가이드( https://positivemh.tistory.com/1058 )
- Python 다운로드 : Windows 10에 Python 설치 가이드( https://positivemh.tistory.com/1059 )
- VS Code 인터프리터 설정 : 인터프리터 설정( https://positivemh.tistory.com/1060 )
- 오라클 접속 : 오라클 19c 파이썬을 이용해 접속 및 쿼리( https://positivemh.tistory.com/1064 )

 

 

pandas 모듈 설치

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
CMD> pip install pandas
Collecting pandas
  Downloading pandas-2.2.1-cp312-cp312-win_amd64.whl.metadata (19 kB)
Collecting numpy<2,>=1.26.0 (from pandas)
  Downloading numpy-1.26.4-cp312-cp312-win_amd64.whl.metadata (61 kB)
     ---------------------------------------- 61.0/61.0 kB 1.1 MB/s eta 0:00:00
Collecting python-dateutil>=2.8.2 (from pandas)
  Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB)
Collecting pytz>=2020.1 (from pandas)
  Downloading pytz-2024.1-py2.py3-none-any.whl.metadata (22 kB)
Collecting tzdata>=2022.7 (from pandas)
  Downloading tzdata-2024.1-py2.py3-none-any.whl.metadata (1.4 kB)
Collecting six>=1.5 (from python-dateutil>=2.8.2->pandas)
  Downloading six-1.16.0-py2.py3-none-any.whl.metadata (1.8 kB)
Downloading pandas-2.2.1-cp312-cp312-win_amd64.whl (11.5 MB)
   ---------------------------------------- 11.5/11.5 MB 14.9 MB/s eta 0:00:00
Downloading numpy-1.26.4-cp312-cp312-win_amd64.whl (15.5 MB)
   ---------------------------------------- 15.5/15.5 MB 24.2 MB/s eta 0:00:00
Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
   ---------------------------------------- 229.9/229.9 kB 13.7 MB/s eta 0:00:00
Downloading pytz-2024.1-py2.py3-none-any.whl (505 kB)
   ---------------------------------------- 505.5/505.5 kB 33.0 MB/s eta 0:00:00
Downloading tzdata-2024.1-py2.py3-none-any.whl (345 kB)
   ---------------------------------------- 345.4/345.4 kB ? eta 0:00:00
Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: pytz, tzdata, six, numpy, python-dateutil, pandas
Successfully installed numpy-1.26.4 pandas-2.2.1 python-dateutil-2.9.0.post0 pytz-2024.1 six-1.16.0 tzdata-2024.1

정상적으로 설치됨

 

 

설치된 버전 확인(vs code에서 실행함)

1
2
3
4
5
6
pandas_version.py
import pandas as pd
print(f"pandas version: {pd.__version__}")
 
결과
pandas version: 2.2.1

pandas 2.2.1 버전임

 

 

엑셀파일저장용 폴더 생성

1
C:\tmp

 

 

multi_ora_to_xls(pandas).py 파일 생성 후 실행

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import oracledb
import pandas as pd
import datetime
 
# DB Connection Info
db_connections = [
    {'un''system''pw''oracle''cs''192.168.137.20/oracle19''port'1521},
    {'un''system''pw''oracle''cs''192.168.137.19/oracle19''port'1521}
]
 
Set Output Filename
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y%m%d_%H%M")
output_filename = f'C:/tmp/output_{formatted_time}.xlsx'
 
# Extract Data and Create DataFrame
df_list = []
for db_info in db_connections:
    un = db_info['un']
    pw = db_info['pw']
    cs = db_info['cs']
    port = db_info['port']
 
    with oracledb.connect(user=un, password=pw, dsn=cs, port=port) as connection:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM v$instance"
            cursor.execute(sql)
 
            columns = [i[0] for i in cursor.description]
            rows = cursor.fetchall()
 
            df = pd.DataFrame(rows, columns=columns)
            df_list.append(df)
 
# Combine DataFrames if there are multiple
if len(df_list) > 1:
    combined_df = pd.concat(df_list, ignore_index=True)
else:
    combined_df = df_list[0]
 
# Write DataFrame to Excel
combined_df.to_excel(output_filename, index=False)
 
print(f"Excel file '{output_filename}' has been created successfully.")

 

 

생성된 파일 확인

output_20240401_2045.xlsx 파일이 생성됨

 

 

엑셀 파일 확인

정상적으로 데이터가 엑셀파일로 저장됨

 

 

참조 : 

https://positivemh.tistory.com/1064

https://positivemh.tistory.com/1065

https://positivemh.tistory.com/1066

https://blog.naver.com/wideeyed/221803761031