프로젝트 중 Python 으로 Oracle 에 접근하여 데이터를 가지고 오는 작업을 수행할 일이 생겨 Mac에서 접근할 수 있는 방법을 정리해보았습니다.
환경 : Mac OS
DB : Oracle
사용언어 : Python
Instant Client for macOS (Intel x86)
cd /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru
./install_ic.sh
# downlaod 폴더에 다운로드가 됨.
/Users/dave/Downloads/instantclient_19_8
Creating dir: /Users/dave/Downloads/instantclient_19_8...
Copying /Volumes/instantclient-basic-macos.x64-19.8.0.0.0dbru files ...
mkdir -p /Users/dave/Oracle/instantclient_19_8/lib
# 위에서 설치한 내용을 위 /Users/dave/Oracle/instantclient_19_8/ 로 복사하기
# 심볼릭 링크 생성
ln -s /Users/dave/Oracle/instantclient_19_8/libclntsh.dylib /Users/dave/Oracle/instantclient_19_8/lib/
sudo vi ~/.zshrc
export ORACLE_HOME=/Users/dave/Oracle/instantclient_19_8
export DYLD_LIBRARY_PATH=/Users/dave/Oracle/instantclient_19_8
export OCI_LIB_DIR=/Users/dave/Oracle/instantclient_19_8
export OCI_INC_DIR=/Users/dave/Oracle/instantclient/sdk/include
export PATH=$PATH:$ORACLE_HOME
source ~/.zshrc
pip install cx_Oracle
python -m pip install cx_Oracle --upgrade
import cx_Oracle
#cx_Oracle.init_oracle_client(lib_dir='/Users/dave/Oracle/instantclient_19_8')
host = ""
port = ""
db_name = ""
user_name = ""
password = ""
dsn_tns = cx_Oracle.makedsn(host, port, service_name=db_name)
conn = cx_Oracle.connect(user=user_name, password=password, dsn=dsn_tns, encoding='UTF-8')
sql_query = """
SELECT
* FROM TABLE WHERE between from_date and to_date
"""
sql_query_formatted = sql_query.format(from_date='20230412', to_date='20230412')
c = conn.cursor()
c.execute(sql_query_formatted)
print(c.fetchall())
c.close()
conn.close()
host = ""
port = ""
db_name = ""
user_name = ""
password = ""
dsn_tns = cx_Oracle.makedsn(host, port, service_name=db_name)
conn = cx_Oracle.connect(user=user_name, password=password, dsn=dsn_tns, encoding='UTF-8')
c = conn.cursor()
#c.execute("SELECT * FROM Table")
c.execute("SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = 'TableName1' ORDER BY COLUMN_ID")
col_data = c.fetchall()
column_list = [col[0] for col in col_data]
c.execute("SELECT * FROM Table WHERE SUBSTR(HG1DDT,1,4) >= '2017'")
data_list = c.fetchall()
df = pd.DataFrame(data_list, columns = column_list)
df = df.fillna('')
c.close()
conn.close()