카테고리 없음
MongoDB - 2
몸이가벼워지는시간
2019. 7. 16. 11:55
오라클 파이썬과 연동하기 위해 설정
# https://www.oracle.com/technetwork/articles/dsl/python-091105.html # 오라클 사이트
# pip install cs_Oracle # 파이썬 오라클 설치
# python -m pip install -upgrade pip # pip 오류날경우 업그레이드
import cx_Oracle
con = cx_Oracle.connect('scott/tiger@localhost/xe')
print(con.version)
con.close()
ex01)
import cx_Oracle
con = cx_Oracle.connect('scott/tiger@localhost/xe')
cur = con.cursor()
cur.execute('select * from dept order by deptno')
쿼리 하나씩 select
# 하나씩 가져오기
# row = cur.fetchone()
# print(row)
# row = cur.fetchone()
# print(row)
"""
(10, 'ACCOUNTING', 'NEW YORK')
(20, 'RESEARCH', 'DALLAS')
"""
# for result in cur:
# print(result, "/", type(result))
"""
(10, 'ACCOUNTING', 'NEW YORK') / <class 'tuple'>
(20, 'RESEARCH', 'DALLAS') / <class 'tuple'>
(30, 'SALES', 'CHICAGO') / <class 'tuple'>
(40, 'OPERATIONS', 'BOSTON') / <class 'tuple'>
"""
cur.close
con.close
쿼리 여러개 조건줘서 가져오기
# 여러개 가져오기
# res = cur.fetchmany(numRows=3)
# print(res, type(res))
# [(10, 'ACCOUNTING', 'NEW YORK'), (20, 'RESEARCH', 'DALLAS'), (30, 'SALES', 'CHICAGO')] <class 'list'>
쿼리 다가져오기
# 다 가져오기
res = cur.fetchall()
print(res, type(res))
# [(10, 'ACCOUNTING', 'NEW YORK'), (20, 'RESEARCH', 'DALLAS'), (30, 'SALES', 'CHICAGO'), (40, 'OPERATIONS', 'BOSTON')] <class 'list'>
ex02) BSON , JSON으로 만들기
# BSON 으로 가공후 JSON 형태로 만들어주는 예제
import cx_Oracle
import time # 내장 모듈
import json # json -> object
# con = cx_Oracle.connect('scott/tiger@localhost/xe')
# 환경변수값을 dsn에 담아두고
dsn = cx_Oracle.makedsn("localhost",1521,"xe")
con = cx_Oracle.connect("scott","tiger",dsn)
start = time.time()
cur = con.cursor()
sql = 'select * from dept'
cur.execute(sql)
rowlist = [] # BSON 문서처럼 넣을 리스트 선언
for row in cur:
# print(row) # 튜플
deptno = row[0]
dname = row[1]
loc = row[2]
# print(deptno , dname, loc) # 출력이상 없음
rowdict = {}
rowdict["deptno"] = deptno
rowdict["dname"] = dname
rowdict["loc"] = loc
rowlist.append(rowdict)
# rowlist 파이썬 LIST 컬렉션 객체
jsonrowlist = json.dumps(rowlist, indent=4, separators=(",","="))
print(rowlist)
""" [
{'deptno': 10, 'dname': 'ACCOUNTING', 'loc': 'NEW YORK'},
{'deptno': 20, 'dname': 'RESEARCH', 'loc': 'DALLAS'},
{'deptno': 30, 'dname': 'SALES', 'loc': 'CHICAGO'},
{'deptno': 40, 'dname': 'OPERATIONS', 'loc': 'BOSTON'}
]"""
print("="*50)
print(jsonrowlist)
""" [
{
"deptno"=10,
"dname"="ACCOUNTING",
"loc"="NEW YORK"
},
{
"deptno"=20,
"dname"="RESEARCH",
"loc"="DALLAS"
},
{
"deptno"=30,
"dname"="SALES",
"loc"="CHICAGO"
},
{
"deptno"=40,
"dname"="OPERATIONS",
"loc"="BOSTON"
}
] """
end = time.time()
print((end-start),' seconds')
""" 몽고 db에 insert 하기위해 - BSON 문서로 가공해야한다.
(10, 'ACCOUNTING', 'NEW YORK')
(20, 'RESEARCH', 'DALLAS')
(30, 'SALES', 'CHICAGO')
(40, 'OPERATIONS', 'BOSTON')
0.0059506893157958984 seconds
"""
cur.close()
con.close()
ex03) 오라클 DB dept 테이블 읽어와서 몽고 DB scottdb/dept 컬렉션 생성후 insert 예제
# 오라클 DB dept 테이블 읽어와서 몽고 DB scottdb/dept 컬렉션 생성후 삽입
import cx_Oracle # 파이썬 + 오라클DB 연결모듈
import pymongo # 파이썬 + 몽고DB 연결 모듈
# 있던 dept 테이블 삭제
# 1. 오라클 연동 con
dsn = cx_Oracle.makedsn("localhost",1521,"xe")
con = cx_Oracle.connect("scott","tiger",dsn)
cur = con.cursor()
# 2. 몽고 연동
myclient = pymongo.MongoClient("mongodb://localhost:27017")
mydb = myclient["scottdb"] # database 생성 (scottdb)
mycol = mydb["dept"] # collection == table 생성
# 3. 오라클 -> 몽고 insert
sql = 'select * from dept'
cur.execute(sql)
for row in cur:
deptno = row[0]
dname = row[1]
loc = row[2]
rowdict = {}
rowdict["deptno"] = deptno
rowdict["dname"] = dname
rowdict["loc"] = loc
mycol.insert_one(rowdict)
cur.close()
con.close()
결과 확인
ex04) 오라클 DB dept 테이블 읽어와서 몽고 DB scottdb/emp 컬렉션 생성후 insert 예제
# 오라클 DB dept 테이블 읽어와서 몽고 DB scottdb/dept 컬렉션 생성후 삽입
import cx_Oracle # 파이썬 + 오라클DB 연결모듈
import pymongo # 파이썬 + 몽고DB 연결 모듈
# 있던 dept 테이블 삭제
# 1. 오라클 연동 con
dsn = cx_Oracle.makedsn("localhost",1521,"xe")
con = cx_Oracle.connect("scott","tiger",dsn)
cur = con.cursor()
# 2. 몽고 연동
myclient = pymongo.MongoClient("mongodb://localhost:27017")
mydb = myclient["scottdb"] # database 생성 (scottdb)
mycol = mydb["emp"] # collection == table 생성
# 3. 오라클 -> 몽고 insert
sql = 'select * from emp'
cur.execute(sql)
rowlist = [] # list 선언
for row in cur:
empno = row[0]
ename = row[1]
job = row[2]
mgr = row[3]
hiredate = row[4]
sal = row[5]
comm = row[6]
deptno = row[7]
rowdict = {}
rowdict["empno"] = empno
rowdict["ename"] = ename
rowdict["job"] = job
rowdict["mgr"] = mgr
rowdict["hiredate"] = hiredate
rowdict["sal"] = sal
rowdict["comm"] = comm
rowdict["deptno"] = deptno
rowlist.append(rowdict)
cur.close()
con.close()
# 몽고디비 insert
x = mycol.insert_many(rowlist)
print(x.inserted_ids)
print("==END==")
ex04) 테이블 생성후 컬럼 추가
"""
sql MongoDB
database database
table collection
row document or BSON document
index index
column field
table joins $lookup
primary key primary key _id UUID
transaction transaction
Oracle MonghDB MySQL
Server Oracle mongod.exe mysqld
Client sqlplus mongo(mongo shell) mysql
"""
import pymongo
import time
myclient = pymongo.MongoClient("mongodb://localhost:27017")
mydb = myclient["scottdb"] # database 생성 (scottdb)
# 1
"""
create table peole(
id number primary key
, user_id varchar2(20)
, age number
, status char(1)
) """
# 1-1. MongoDB 에서 people collection 생성
# mycol = mydb["dept"] # collection == table 생성
# mydb.createCollection("people") # 명시적 테이블 생성
# people 이란 테이블을 만들지 않아도 insert하는 순간 생성되서 들어가진다.
"""
mydb.people.insert_one({
"user_id":'admin',
"age":20,
"status":"A"
}) """
# 2 people 테이블에 join_date 컬럼 추가
"""
alter table people
add join_date date
"""
# 2-1. MongoDB 필드 추가
"""
mydb.people.update_many(
{}, # 업데이트 조건(where)
{"$set":{"join_date":None }} # (set)
) """
# 3-1 필드 삭제
"""
mydb.people.update_many(
{}, # 업데이트 조건(where)
{"$unset":{"join_date":"" }} # (set)
) """
print("==END==")