Programming

[Database] Python 에서 Oracle DB 연동

better_coco 2023. 4. 5. 08:47

 

Step01. oracledb package 설치

pip install oracledb

- 찾아보면 기존에 많이 사용되던 cx_Oracle package 가 있고, oracledb package 가 있다.

- cx_Oracle 이 업그레이드 된 것이 oracledb 라고 하며, 권한이 일부 달라 보인다. (client 부분)

- cx_Oracle 로 시도해보다가 환경설정 부분에서 잘 안 되는 부분이 있어서, oracledb 를 사용했다.

 

** 자세한 내용은 하단 링크 참고

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

 

python-oracledb - Python Driver for Oracle Database

Optional use of Oracle Client 11.2, 12, 18, 19 or 21 libraries for advanced Oracle Database functionality. Oracle's standard cross-version interoperability, allows easy upgrades and connectivity to different Oracle Database versions.

oracle.github.io

 

Step02. 필요한 파일 다운로드

https://www.oracle.com/database/technologies/instant-client/macos-intel-x86-downloads.html

 

Instant Client for macOS (Intel x86)

We’re sorry. We could not find a match for your search. We suggest you try the following to help find what you’re looking for: Check the spelling of your keyword search. Use synonyms for the keyword you typed, for example, try "application" instead of

www.oracle.com

 

instantclient-basic-macos.x64-19.8.0.0.0dbru.zip

instantclient-sdk-macos.x64-19.8.0.0.0dbru.zip

instantclient-sqlplus-macos.x64-19.8.0.0.0dbru.zip

 

- 다운받은 압축 파일들을 푸니, 아래와 같은 형태로 압축이 풀어졌다. windows 에서는 해당 path 를 환경변수로 설정해주는 부분이 있는데, 나는 코드 상에 path 를 하드코딩해서 넣어주는 식으로 우선 진행했다. (아래 참고)

 

 

Step03. Python 코드 작성

 

import oracledb
import os
import pandas as pd

un = os.environ.get('PYTHON_USERNAME')
pw = os.environ.get('PYTHON_PASSWORD')
cs = os.environ.get('PYTHON_CONNECTSTRING')

oracledb.init_oracle_client(lib_dir="/Desktop/oracle/instantclient_19/basic")
con = oracledb.connect(user='사용자이름', password='비밀번호', dsn='localhost')
cursor = con.cursor()

#쿼리문
sql = """select * from totaldatasets"""

cursor.execute(sql)
x = cursor.fetchall()
df = pd.DataFrame(x)

cursor.close()
con.close()

 

위의 코드로 oracle DB 로 쿼리를 날려서 데이터를 뽑아보면, 아래와 같이 잘 나오는 걸 확인할 수 있다.

 

Python 에서 쿼리로 뽑은 데이터