Python에서 cx_Oracle 환경 구성
파이썬에서 Oracle 연결은 파이썬 패키지뿐만 아니라,
$ pip install cx_Oracle
네이티브 모듈도 함께 설치를 해야 합니다.
// cx_Oracle 8 Installation
// ; https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html
$ sudo mkdir -p /opt/oracle
$ cd /opt/oracle
$ sudo wget https://download.oracle.com/otn_software/linux/instantclient/216000/instantclient-basic-linux.x64-21.6.0.0.0dbru.zip
$ sudo unzip instantclient-basic-linux.x64-21.6.0.0.0dbru.zip
$ sudo apt install libaio1
$ sudo sh -c "echo /opt/oracle/instantclient_21_6 > /etc/ld.so.conf.d/oracle-instantclient.conf"
$ sudo ldconfig
위와 같이만 구성해 주면 이제 cx_Oracle.connect에 적절한 연결 정보를 전달해 실행할 수 있습니다. 예를 들어,
닷넷의 경우 이렇게 연결 문자열을 구성했다면,
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.100.50)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=hr;Password=hrpass;
파이썬에서도 유사하게 이런 식으로 전달하면 됩니다.
dsn = """(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.0.8)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=XE)))"""
con = cx_Oracle.connect(user='hr', password='hrpass', dsn=dsn)
혹은 좀 더 약식으로 id, password 및 "HOST:PORT/SERVICE_NAME" 형식으로 다음과 같이 연결 테스트를 할 수 있습니다.
import cx_Oracle
oc = cx_Oracle.connect('hr', 'hrpass', '192.168.100.50:1521/XE')
참고로, dockerfile로 구성한다면 instantclient-basic-linux.x64-21.6.0.0.0dbru.zip 파일을 dockerfile 위치에 미리 복사해 둔 후 (혹은 그것조차도 dockerfile에서 wget으로 받아두거나) 이런 식으로 구성하면 됩니다.
FROM python:3.8-slim-buster
...[생략]...
RUN mkdir -p /opt/oracle
RUN cd /opt/oracle
COPY instantclient-basic-linux.x64-21.6.0.0.0dbru.zip /opt/oracle/ora_native.zip
RUN unzip ora_native.zip
RUN apt install libaio1
RUN sh -c "echo /opt/oracle/instantclient_21_6 > /etc/ld.so.conf.d/oracle-instantclient.conf"
RUN ldconfig
...[생략]...
이후의 python 내에서 사용하는 방법은 일반적인
dbapi2 인터페이스를 따릅니다.
혹시나 다음과 같은 오류가 발생한다면?
DatabaseError at /bbs/oracletest
DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help
네이티브 모듈(instantclient-basic-linux.x64-21.6.0.0.0dbru.zip)을 설치하지 않아서 그런 것입니다.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]