59doit
[ SQL ] Oracle connect DB #1 _ Python 이용 본문
반응형
Python
1. C:드라이브에 OracleTest 폴더 생성
2. OracleTest폴더에 driver ojdbc6 저장
ojdbc6 위치 : # C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
3. SQL developer에서 scott계정으로 table 생성
ID : sys / PW : 1234
create table py_table( id varchar(50) primary key, pass varchar(30) not null, name varchar(25) not null, age number(2) ); insert into test_table values('hong', '1234', '홍길동', 35); insert into test_table values('kim', '5678', '김길동', 45); select * from test_table; commit; |
▶ Python
import cx_Oracle
import os
# 한글 지원 환경
os.putenv('NLS_LANG', '.UTF8')
# Path 설정
LOCATION = r"c:/instantclient_21_7"
os.environ["PATH"] = LOCATION + ";" + os.environ ["PATH"]
# DB 연결
connect = cx_Oracle.connect("scott", "tiger", "localhost:1521/xe")
cs = connect.cursor()
ex) sql 연결
# 1. 데이터 추가(insert)
sql = "insert into py_table values('kang', '1234', '강감찬', 45)"
cs.execute(sql) # SQL문
# 2. 데이터 보기
cs.execute("select * from py_table") # SQL문
for i in cs:
print(i)
# ('hong', '1234', '홍길동', 35)
# ('kim', '5678', '김길동', 45)
# ('kang', '1234', '강감찬', 45)
# 3. 나이가 40 세 이상인 record => test_table
sql = "select * from test_table where age >= 40"
cs.execute(sql)
# 4. name 이 '강감찬'인 데이터의 age 를 40 으로 수정 & 수정된 레코드 조회
sql = "update test_table set age = 40 where name = '강감찬'"
cs.execute("select * from test_table")
for i in cs:
print(i)
# 5. 수정된 레코드 조회
sql = "select * from test_table where name = '강감찬'"
cs.execute(sql)
# ('kang', '1234', '강감찬', 40)
# 6. name 이 '홍길동'인 레코드 삭제
sql = "delete from test_table where name = '홍길동'"
cs.execute(sql)
# 7. 전체 레코드 조회
sql = "select * from test_table"
cs.execute(sql)
for i in cs:
print(i)
# ('kim', '5678', '김길동', 45)
# ('kang', '1234', '강감찬', 40)
# 사용 후 close
해줘야 오라클에서 해당 테이블 편집 할 수 있음
cs.close()
connect.commit()
connect.close()
close 안 할 경우 오라클 에러
반응형
'Programming > SQL 기초' 카테고리의 다른 글
[ SQL ] 데이터베이스 #2 JDK 설치 (0) | 2022.12.07 |
---|---|
[ SQL ] 데이터베이스 #1 (1) | 2022.12.06 |
[ SQL ] Oracle connect DB #1 _ R 이용 (0) | 2022.12.06 |
Live SQL - Code Library (0) | 2022.10.20 |
SQL 참고 사이트 (0) | 2022.10.14 |
Comments