728x90
DB 연동
python 프로그램에서 여러 DB(Oracle, My SQL등)과 연동이 가능한데요
연동을 위해서는 sql과 python을 연결하는 라이브러리 설치가 필요합니다
-> (드라이버)라이브러리가 필요함
Oracle 라이브러리 설치
(cmd 관리자 권한 실행하여 입력)
python -m pip install cx_Oracle --upgrade
위 코드를 cmd에 입력!
이제 라이브러리를 설치했으면 Python(저는 pycharm을 사용했어요) 에 가서 DB를 아래와 같이 연결합니다
** user,pw,dns는 각 DB를 만들때 입력했던 값으로 속성에서 확인 가능합니다
import cx_Oracle
user = '유저이름'
pw = 'password'
dns = 'localhost: ddd/xe"
con = cx_Oracle.connect(user,pw,dns, encoding="utf-8")
con.close()
python과 Oracle을 연결해주는 연결통로 역할이 Cursor객체인데요
with con.cursor as cur: 로 Cursor 객체를 형성합니다
호출 방법은 다음과 같은 구문을 사용할 수 있습니다
- cur.execute (단일 SQL문을 보낼 때)
- cur.executemany (다중 SQL문을 보낼 때)
- cur.fetchone() (단일 레코드를 받을 때)
- cur.fetchall() (여러 레코드를 받을 때)
- 총 레코드개수는 cur.rowcount 사용
단일행 전달)
with con.cursor() as cur:
cur.execute("select no, name from school where no = 50")
#일반 sql문과 달리 세미콜론(;)이 없어야 함
result = cur.fetchone()
print(result)
만일 여기서 조건 값에 동적인 변수를 넣고 싶다면 SQL구문에 :변수명 을 넣으면 됩니다
no = input("희망번호 입력")
with con.cursor() as cur:
cur.execute("select no, name from dept where no = :xxx",xxx = no)
result = cur.fetchone()
print(result)
다중행 전달)
with con.cursor() as cur:
cur.execute("select no, name, loc from dd")
result = cur.fetchall()
print(result)
DML 실행방법) → con.commit 필요
Insert
with con.cursor() as cur:
cur.execute("insert into table(no,name) values(:no,:name)",
no=12, name="a")
con.commit()
Update
with con.cursor() as cur:
cur.execute("update table set dname = :dname, loc = :loc where no = :no",
dname = "as", loc = "bb", no = 100)
con.commit()
Delete
with con.cursor() as cur:
cur.execute("delete from table where no = :no",no = 100)
con.commit()
728x90
반응형
'Python' 카테고리의 다른 글
다중 리스트 원소 포함 여부 파악하기 (0) | 2022.09.27 |
---|---|
파이썬 Map function 다중 변수, 다중 리스트 적용방법 (0) | 2022.09.27 |
Python 딕셔너리 키 값, value 값으로 정렬하는 법 (1) | 2022.09.21 |
Heapq 알고리즘 개념 및 활용방법 정리 (1) | 2022.09.21 |
Python List append/extend와 +=의 차이점 정리 (1) | 2022.09.20 |
댓글