오라클과 파이썬 연동하기
연동
오라클 database --------------- 파이썬 ( 통계구현, 시각화, 머신러닝, 업무자동화 )
비즈니스 데이터
(정형화된 데이터)
데이터의 구조에 따른 종류 3가지
1. 정형 데이터 : 관계형 데이터베이스(RDBMS)에 저장된 데이터
2. 반정형 데이터 : html, 웹로그 데이터
3. 비정형 데이터 : 텍스트(SNS), 동영상, 이미지 데이터
오라클을 파이썬과 연동하는 이유
1. 오라클 데이터베이스에서 실시간으로 변하는 데이터를
CSV파일로 매번 내리려면 자주 내려야 하므로 그냥 연동시키는 게 편리하다
2. 파이썬의 통계 구현, 시각화, 머신러닝 구현, 업무 자동화를 사용 가능
3. 이미지를 숫자로 변환한 뒤 오라클 DB에 저장하여 관리하는 것이 가능하다.
-> 백업 및 복구 가능, 효율적 DATA 관리 가능
# 오라클과 파이썬 연동하기
1. 도스창을 열고, 리스너의 상태를 확인
* 리스너 : 외부에서 오라클에 접속하려면 리스너를 통해서만 접속 가능
리스너가 접속을 허용해줘야 접속이 된다.
접속하기 위해서는 리스너가 가지고 있는 정보 중 3가지를 확인해야한다.
(1) ip 주소 (건물 주소)
(2) 포트번호 (건물안의 복도)
(3) 서비스 이름 (회사 이름)
cmd -> lsnrctl status 를 입력
ip 주소 : localhost
포트 번호 : 1521
서비스 이름 : orcl 확인
2. 실행창에
(sql 만들었을 때 아이디 : system 비밀번호 : oracle_4U)
sqlplus system/oracle_4U@localhost:1521/orcl as sysdba 입력
3. 아나콘다 프롬프트창을 열고 (cmd 아님) cx_Oracle 모듈을 설치
conda install cx_Oracle
4. 파이썬에서 오라클과 연동하는 코드를 작성
# cx_Oracle 모듈을 통해 파이썬과 연동하기1
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl') # 오라클 주소
print(dsn)
# cx_Oracle 모듈을 통해 파이썬과 연동하기2 ( emp 전체 테이블 출력하기 )
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn) # 오라클 접속 유저 정보
cursor=db.cursor() # 결과 데이터를 담을 메모리 이름을 cursor로 선언
cursor.execute("""select * from emp """) # 작성한 SQL 쿼리문의 결과는 cursor 메모리에 담긴다
row=cursor.fetchall() # cursor 메모리에 담긴 결과를 한 번에 row 변수에 담는다.
emp=pd.DataFrame(row)
print(emp)
# 사원들의 월급을 막대 그래프로 표현하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select ename,sal from emp """)
row=cursor.fetchall()
emp=pd.DataFrame(row)
emp.index=list(emp[0]) # (KING~MILLER)
emp.plot(kind='bar',color='skyblue')
# 직업별 최대 월급을 막대 그래프로 출력하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select job,max(sal) from emp group by job""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
emp.index=list(emp[0])
emp.plot(kind='bar',color='skyblue')
# EMP 테이블 확인하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
print(emp)
** 확인해보면 컬럼명이 임의의 숫자로 되어있어서 판다스 문법을 사용할 수가 없다
# 컬럼명 출력하기1
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
colname=cursor.description
print(colname)
# 컬럼명 출력하기 2
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
colname=cursor.description
for i in colname:
print(i[0])
# 컬럼명을 리스트에 담기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
colname=cursor.description
col=[]
for i in colname:
col.append(i[0].lower())
print(col)
# 위 컬럼 리스트를 데이터에 결합시키기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
colname=cursor.description
col=[]
for i in colname:
col.append(i[0].lower())
emp=pd.DataFrame(list(row),columns=col) #list(row)는 열로, col은 행으로 표현
print(emp)
# 판다스 문법을 이용해서 이름과 월급을 출력하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
colname=cursor.description
col=[]
for i in colname:
col.append(i[0].lower())
emp=pd.DataFrame(list(row),columns=col)
print(emp[['ename','sal']])
# 판다스 문법을 통해 월급이 3000 이상인 사원의 이름과 월급 출력하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select *
from emp
""")
row=cursor.fetchall()
colname=cursor.description
col=[]
for i in colname:
col.append(i[0].lower())
emp=pd.DataFrame(list(row),columns=col)
print(emp[['ename','sal']][emp['sal']>=3000])
# 사원의 이름과 부서 위치를 조인을 통해 출력하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select e.ename,d.loc
from emp e, dept d
where e.deptno=d.deptno
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
print(emp)
# 부서 위치별 월급 총합 출력하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select d.loc, sum(e.sal)
from emp e, dept d
where e.deptno=d.deptno
group by d.loc
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
print(emp)
# 부서 위치별 월급 총합을 막대 그래프로 표현하기
import cx_Oracle
import pandas as pd
dsn=cx_Oracle.makedsn("localhost",1521,'orcl')
db=cx_Oracle.connect('scott','tiger',dsn)
cursor=db.cursor()
cursor.execute("""select d.loc, sum(e.sal)
from emp e, dept d
where e.deptno=d.deptno
group by d.loc
""")
row=cursor.fetchall()
emp=pd.DataFrame(row)
emp.index=list(emp[0])
emp.plot(kind='bar',color='skyblue')
'나 취준생 > 파이썬' 카테고리의 다른 글
웹 스크롤링 연습 ( 유튜브 댓글 ) (0) | 2020.12.22 |
---|---|
MYSQL, 파이썬 연동 (0) | 2020.12.21 |
구글 이미지 크롤링 (0) | 2020.12.18 |
감정 분석 + 워드 클라우드 (0) | 2020.12.18 |
워드 클라우드 그리기 (0) | 2020.12.18 |