Open Source Software
Python - Oracle Database 연결 샘플 코드
간디와같은마음
2022. 6. 10. 17:59
Reference
아래 사이트를 참조하여 작성한 코드입니다.
사전 조건: cx_Oracle 모듈을 설치("python -m pip install cx_Oracle --upgrade") 되어 있어야 하고, 오라클 클라이언트 라이브러리가 Path에 잡혀 있어야 합니다.
import logging
import cx_Oracle
username = 'system'
password = 'Welcome123'
dsn = '150.136.212.183/orclpdb1'
port = 1521
encoding = 'UTF-8'
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
connection = cx_Oracle.connect(username, password, dsn, encoding=encoding)
except Exception as ex:
logger.error("ERROR: Could not connect to database.")
logger.error(ex)
print('Could not connect to database:', ex)
logger.info("SUCCESS: Connecting database succeeded")
try:
cursor = connection.cursor()
sql = "select * from hr.departments"
cursor.execute(sql)
except Exception as ex:
logger.error("ERROR: Could not fetch data.")
logger.error(ex)
print('Could not fetch data:', ex)
logger.info("SUCCESS: Fetching data succeeded")
rows = cursor.fetchall()
print(rows)
cursor.close()
connection.close()
<END>