본문 바로가기
Be Smart/Python

[python] 오라클 DB 파이썬과 연동하기 사용법

by 반월하 2021. 11. 8.
728x90

사전 준비물

① instant-client download

② cx-oracle download


[사전 준비] instant-client download

instant-client download

자신에게 맞는 OS를 선택하여 다운로드를 클릭한다.

자신의 오라클 버전을 확인한 후

SELECT * FROM PRODUCT_COMPONENT_VERSION;

자신에게 맞는 버전을 다운로드 한다.

그 후 적당한 위치에 압축을 푸는데 C Drive에 푸는 것을 추천한다.


[사전 준비] cx-oracle download

-아나콘다를 사용할 경우

- Python terminal에서

pip install cs-oracle을 이용해 설치


[접속] 접속 정보

CATEGORY
HOST IP
PORT port
SID sid
ID id
PW pw

 

[접속] NLS 맞추기

SELECT USERENV('LANGUAGE') FROM dual

밑에 환경 변수로 활용

해당 결과는 os.putenv로 활용된다.


[접속] TEST SAMPLE

일반 활용

import os 
os.chdir('C:\\instantclient-basic-windows.x64-11.2.0.4.0\\instantclient_11_2') 
os.putenv('NLS_LANG', 'AMERICAN_AMERICA.UTF8') 

import cx_Oracle 
db = cx_Oracle.connect('id','pw', 'ip:port/sid') 

print('{}'.format(db.version)) 

sql = 'select * from dual' 
cursor = db.cursor() 
cursor.execute(sql) 

for row in cursor: 
    print(row) 

cursor.close() 
db.close()

 

pandas 활용

import os 
os.chdir('C:\\instantclient-basic-windows.x64-11.2.0.4.0\\instantclient_11_2') 
os.putenv('NLS_LANG', 'AMERICAN_AMERICA.UTF8') 

import cx_Oracle 
db = cx_Oracle.connect('id','pw', 'ip:port/sid') 

print('{}'.format(db.version)) 

import pandas as pd 

datas = pd.read_sql(sql='select * from dual', con = db) 

db.close

 


참고

 

ojdbc6.jar 받는 위치

 

NLS 확인하기

SELECT * FROM NLS_DATABASE_PARAMETERS

728x90

댓글