Microsoft MVP성태의 닷넷 이야기
스크립트: 39. Python에서 cx_Oracle 환경 구성 [링크 복사], [링크+제목 복사],
조회: 7518
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

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)을 설치하지 않아서 그런 것입니다.


참고로, 네이티브 모듈 없이 cx_Oracle 패키지만 내려받아 사용하면 cx_Oracle.connect는 (오류 없이) None을 반환합니다. 그런 탓에 None 체크 없이 곧바로 cursor를 사용하려는 경우,

import cx_Oracle
con = cx_Oracle.connect('...', '...', '...')
cursor = con.cursor()

이런 오류가 발생할 수 있습니다.

Traceback (most recent call last):
  File "/home/testusr/.local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 435, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  ...[생략]...
  File "/mnt/c/temp/testprj/p38fastapi/main.py", line 255, in cxoracle_test
    text1 = test_cxoracle_1()
  File "/mnt/c/temp/testprj/p38fastapi/main.py", line 265, in test_cxoracle_1
    cursor = con.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'

또는 with 문과 사용한다면,

import cx_Oracle

with cx_Oracle.connect(user='...', password='...', dsn='...') as con:
    with con.cursor() as cursor:
        pass

connect 문에서 다음과 같은 예외가 발생합니다.

Traceback (most recent call last):
  File "/home/testusr/.local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 435, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  ...[생략]....
  File "/mnt/c/temp/testprj/p38fastapi/main.py", line 286, in test_cxoracle_2
    with cx_Oracle.connect(user='...', password='...', dsn='...') as con:
AttributeError: __enter__





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/21/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12310정성태9/3/202010333오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/202010101개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011341개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202012129오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202010324오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202011170Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/202010127개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010293개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202010215.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202010506오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/20209921.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202010847.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
12298정성태8/27/202010598오류 유형: 640. livekd - Could not resolve symbols for ntoskrnl.exe: MmPfnDatabase
12297정성태8/25/20209790개발 환경 구성: 503. SHA256 테스트 인증서 생성 방법
12296정성태8/24/202010209.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger파일 다운로드1
12295정성태8/24/20209662오류 유형: 639. Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket ,,,
12293정성태8/24/202010991Windows: 171. "Administered port exclusions" 설명
12292정성태8/20/202012291.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202011209오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
12290정성태8/11/202011878.NET Framework: 931. C# - IP 주소에 따른 국가별 위치 확인 [8]파일 다운로드1
12289정성태8/6/20209390개발 환경 구성: 502. Portainer에 윈도우 컨테이너를 등록하는 방법
12288정성태8/5/20209376오류 유형: 637. WCF - The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.
12287정성태8/5/20209842오류 유형: 636. C# - libdl.so를 DllImport로 연결 시 docker container 내에서 System.DllNotFoundException 예외 발생
12286정성태8/5/202010700개발 환경 구성: 501. .NET Core 용 container 이미지 만들 때 unzip이 필요한 경우
12285정성태8/4/202011104오류 유형: 635. 윈도우 10 업데이트 - 0xc1900209 [2]
12284정성태8/4/202010400디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...