본문 바로가기

메가존 클라우드 2기 교육/Python, Go lang

Python - Oracle DB연동

오라클DB 설치

https://www.oracle.com/database/technologies/xe-prior-release-downloads.html

 

XE Prior Release Archive

Getting Started: Support Oracle Database Express Edition (XE) is a community supported edition of the Oracle Database family. Please go to the Oracle Database XE Community Support Forum for help, feedback, and enhancement requests. Note: Oracle Support Ser

www.oracle.com

다운받은 파일을 설치하자.

과정 자체가 단순하므로 따로 과정을 적진 않겠다.

단, 설정한 암호는 반드시 기억하자.


SQLDeveloper

https://www.oracle.com/database/sqldeveloper/technologies/download/

 

Oracle SQL Developer Downloads

This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already

www.oracle.com

맞는 버전을 다운로드 하고, sqldeveloper.exe를 실행하자

만일, jvm.dll 오류가 난다면,

sqldeveloper\jdk\jre\bin\msvcr100.dll 파일을 Windows\System32폴더에 넣어주자

실행화면
좌측의 ' + ' 버튼을 누르자
이름과 각자 설정하고, 비밀번호는 설치때 사용한 비밀번호로, 나머지는 그림과 같이 하자
테스트를 눌러 성공하는지 확인하자.
이제 SQL문을 사용해보자.

실습 계정 HR 계정 로그인

alter user hr identified by hr account unlock;
system에서 hr 계정을 언락해주자. (생성이 아님)
접속 이름, 사용자 이름, 비밀번호 모두 hr로 하겠다.
hr 계정 성공적으로 만들어졌다.
select * from tab;
sql문도 정상적으로 작동한다.

 

 

 

 


파이썬 오라클 연동

윈도우에 cx_Oracle 설치

cmd창을 킨다.

python -m pip install cx_Oracle --upgrade

 

쥬피터 노트북에서 연동

쥬피터 노트북을 실행한다.

새 파이썬 파일을 만들자.
! pip install cx_Oracle

혹시 모르니 쥬피터에도 설치를 했다.

import cx_Oracle as cx

conn = cx.connect("hr", "hr", "localhost:1521/xe")
cursor = conn.cursor()
cursor.execute('select * from jobs')
print(cursor.fetchall())
접속이 잘 된다.

 여기서, cx.connect("접속 이름", "사용자 이름", "주소:포트/sid)) 로 원하는 db의 원하는 사용자로 연결

import pandas as pd
import cx_Oracle as cx

conn = cx.connect("hr", "hr", "localhost:1521/xe")
cursor = conn.cursor()
query ='select * from jobs'
df = pd.read_sql(query, con=conn)
print(df)
print(df.info() )
pandas도 잘 된다.