본문 바로가기
Python/Fast API

[Fast API] SQLAlchemy로 Oracle DB 연결하기

by ete-llorona 2022. 12. 28.

 

FastAPI 공식 홈페이지에서는 SQLAlchemy 로 다음 RDBMS 에 연결할 수 있다고 소개한다.

 

  • PostgreSQL
  • MySQL
  • SQLite
  • Oracle
  • Microsoft SQL Server, etc

https://fastapi.tiangolo.com/ko/tutorial/sql-databases/

 

SQL (Relational) Databases - FastAPI

SQL (Relational) Databases Warning The current page still doesn't have a translation for this language. But you can help translating it: Contributing. FastAPI doesn't require you to use a SQL (relational) database. But you can use any relational database t

fastapi.tiangolo.com

 

튜토리얼에는 SQLite, PostgreSQL 예시만 나와있어서, Oracle DB에 연결할 때 겪었던 시행착오를 기록해본다. 

SQLAlchemy 공식 홈페이지 내용과 구글링 결과를 참고했다. 

 

 

 

1. 라이브러리 설치

 

FastAPI 에서 Oracle DB를 연결하려면 먼저 sqlalchemy, cx_Oracle 라이브러리 두개를 설치해야 한다.

 

pip install sqlalchemy

pip install cx_Oracle

 

 

 

2. Oracle DB 연결

 

create_engine에 본인이 연결하고자 하는 database url 을 적어주면 된다. 

SQLAlchemy 공식 홈페이지에 따르면 database url은 다음과 같은 규칙에 맞게 작성해야 한다.

dbname이 없을 때는 port까지만 작성하면 된다. 

 

oracle+cx_oracle://user:pass@hostname:port[/dbname][?service_name=<service>[&key=value&key=value...]]

 

https://docs.sqlalchemy.org/en/14/dialects/oracle.html#dialect-oracle-cx_oracle-connect

 

Oracle — SQLAlchemy 1.4 Documentation

Oracle Support for the Oracle database. The following table summarizes current support levels for database release versions. DBAPI Support The following dialect/DBAPI options are available. Please refer to individual DBAPI sections for connect information.

docs.sqlalchemy.org

 

 

create_engine() 부분에 url을 바로 적는 것보다 일정한 양식을 갖춰 작성하면 가독성이 높아진다. 

아래 양식은 구글링 하다가 github에서 누가 공유한 예제를 사용했다. 출처는 아래 주소에 남겨두었다.  

 

import pandas as pd
from sqlalchemy import create_engine


oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}'
# oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}/{database}'


engine = create_engine(
    oracle_connection_string.format(
        username='C##MADANG',
        password='madang',
        hostname='localhost',
        port='1521',
#        database='',
    )
)

data = pd.read_sql("SELECT * FROM BOOK", engine) # 조회한 결과를 데이터프레임으로 저장할 경우

 

 

출처: https://gist.github.com/DGrady/7fb5c2214f247dcff2cb5dd99e231483

 

Example of querying an Oracle database using Python, SQLAlchemy, and Pandas

Example of querying an Oracle database using Python, SQLAlchemy, and Pandas - oracle-query.org

gist.github.com

 

 

 

3. sqlalchemy dpi-1047: cannot locate a 64-bit oracle client library 에러 발생 시 대처법

 

 

구글링해보면 위의 오류가 발생하는 사례가 많다. 

이를 해결하기 위해서는 Oracle 공식 홈페이지에서 버전에 맞는 Instant Client Package 를 다운받는다. 

 

zip 파일 압축을 해제한 후 해당 경로를 복사한 뒤에 

cx_Oracle.init_oracle_client()에 아래와 같이 작성하거나,

시스템 환경 변수 편집에서 PATH 에 새로 다운 받은 Instant Client Package 폴더 경로를 추가해주면 정상적으로 작동된다. (안되는 경우가 간혹 있다. 확실한 방법은 cx_Oracle.init_oracle_client()로 직접 지정하는 방법이다. )

 

import cx_Oracle

cx_Oracle.init_oracle_client(lib_dir="C:/oraclexe/app/oracle/instantclient_11_2")

 

오라클 공식 홈페이지: https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html

 

Instant Client for Microsoft Windows (x64) 64-bit

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

 

 

 

4. 전체 코드

 

import cx_Oracle
import pandas as pd
from sqlalchemy import create_engine


cx_Oracle.init_oracle_client(lib_dir="C:/oraclexe/app/oracle/instantclient_11_2")
oracle_connection_string = 'oracle+cx_oracle://{username}:{password}@{hostname}:{port}'

engine = create_engine(
    oracle_connection_string.format(
        username='C##MADANG',
        password='madang',
        hostname='localhost',
        port='1521',
    )
)

data = pd.read_sql("SELECT * FROM BOOK", engine) # 조회한 결과를 데이터프레임으로 저장할 경우

 

 

댓글