1. 시작하며

이 글은 윈도우 환경에서 Python이 설치되어있고,

AWS RDS가 구축되어 있으며 Oracle과 연동되어있는 상태에서 시작합니다.

이 준비가 되어있지 않으신 분들은 구글링을 통해 먼저 진행해주세요. 

 

 

 

2.  cx_Oracle 설치

cmd창에서 pip install cx_Oracle 명령어를 실행하여 cx_Oracle을 설치합니다.

pip install cx_Oracle

 

 

 

3. Python bit 확인

사용 중인 Python bit를 확인합니다. 아래 코드로 확인할 수 있습니다.

import platform
print(platform.architecture())

 

 

 

4. Oracle Instant Clinet 다운로드

사용하는 Python bit에 맞는 Oracle Instant Clinet를 오른쪽 링크에서 다운로드합니다. (32bit, 64bit)

다운로드받은 zip파일을 압축 해제한 후 원하는 위치로 옮깁니다. 저는 C드라이브로 옮겼습니다.

 

 

 

5. 환경변수 추가

윈도우키를 누르고 "환경 변수"라고 검색해서 [시스템 환경 변수 편집]을 클릭한 후,

시스템 속성창에서 [환경 변수]를 클릭합니다.

 

 

[시스템 변수]에서 [Path]를 클릭 후 [편집]을 클릭합니다.

환경 변수 편집창에서 [새로 만들기]를 클릭 후 4번에서 압축 해제한 폴더의 경로를 추가합니다.

폴더의 경로는 파일 탐색기에서 경로 부분을 클릭하면 복사할 수 있습니다.

 

 

 

6. 재부팅

환경변수를 추가했으니 재부팅합니다.

 

 

 

7. DB 연결 예제

RDS의 사용자 이름, 비밀번호, 호스트 이름, 포트, SID를 확인합니다. sqldeveloper로 확인하면 편합니다.

오른쪽 사진은 예제에 사용할 SAMPLETABLE입니다.

 

 

import cx_Oracle
import os
import pandas as pd # pandas를 사용하지 않을거면 지워도 됩니다.

# 한글 설정
os.putenv('NLS_LANG', '.UTF8')

# DB 연결
connection = cx_Oracle.connect("사용자 이름/비밀번호@호스트이름:포트/SID")
cursor = connection.cursor()

# 쿼리 실행
cursor.execute("insert into SAMPLETABLE(id, name) values ('%d', '%s')" % (3, "테스트삼")) # insert 예제 1
cursor.execute("insert into SAMPLETABLE(id, name) values (:2, :3)", (4, "테스트사")) # insert 예제 2
cursor.execute("insert into SAMPLETABLE(id, name) values (5, '테스트오')") # insert 예제 3
cursor.execute("update SAMPLETABLE set name='사테스트' where id = 4") # update 예제
cursor.execute("delete from sampletable where id = 5") # delete 예제
cursor.execute("select * from SAMPLETABLE") # select 예제
result = cursor.fetchall()
print("실행 결과\n", "-" * 70, "\n", result, "\n\n\n")

# pandas로 확인하기 (pandas를 사용하지 않을거면 아래 세 줄은 지워도 됩니다.)
df = pd.DataFrame(result)
df.columns=[row[0] for row in cursor.description]
print("pandas 실행 결과\n", "-" * 70, "\n", df)

# commit
connection.commit()

# close
cursor.close()
connection.close()

예제 코드와 실행결과입니다.

insert 예제 1, 2, 3을 보면 다양한 방법으로 변수를 입력할 수 있다는 것을 알 수 있습니다. 

 

 

 

8. 참고한 사이트

https://medium.com/@praneeth.jm/connecting-to-an-oracle-rds-instance-from-python-b532b1d7b7ea

+ Recent posts