기존 postgresql 설치와 설정에 이어 두번째 시간입니다. 이번에는 직접 데이터를 적재하는 방법입니다.
지난번 내용을 모르신다구요? 걱정마세요 하단에 링크를 첨부합니다!
postgresql을 python으로 사용하기 위해서는 패키지 설치가 필요합니다.
1. python 패키지 설치에 도움을 주는 또다른 친구 pip를 사용해 설치합니다.
pip install psycopg2-binary
2. 패키지 설치가 끝났다면 사용을 위해 import 해줍니다.
(datetime은 밑에 코드와 관련이 있어서 했습니다)
import psycopg2
from datetime import datetime
3. DB connecttion을 해보겠습니다.
def db_connection():
connection = psycopg2.connect(
host={host},
port={post},
user={db user},
password={db password},
database={database name}
)
cursor = connection.cursor()
return connection, cursor
return되는 값 중 connection에는 연결정보가 저장되어 있고,
cursor로는 SQL 쿼리를 실행하고 쿼리의 결과를 검색하거나 조작할 수 있게 됩니다.
둘다 return하는 이유는 connection을 끊을 때 둘다 닫아줘야 하기 때문입니다.
4. 데이터를 insert 해보겠습니다
os column은 varchar, time_stamps는 timestamp, test_results는 varchar type으로 설정되어 있습니다.
테스트 결과가 실패면 error code와 error reason 내용을 가져와 적재하고, 성공이면 적재하지 않도록 했습니다.
def insert_data(connection, cursor, self, result_data):
data_to_insert = {
"os": {platform OS},
"time_stamps": datetime.now(),
"test_results": {test result},
}
# 추가 삽입 데이터 (테스트 결과 실패일때 추가 정보 입력)
if result_data.get("test_result") == 'FAIL':
data_to_insert["err_code"] = {error code}
data_to_insert["err_reason"] = {error reason}
else:
data_to_insert["err_code"] = None
data_to_insert["err_reason"] = None
# SQL 쿼리 생성 및 실행
insert_query = """
INSERT INTO test_result (
os, time_stamps, test_results, err_code, err_reason
) VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (
data_to_insert["os"],
data_to_insert["time_stamps"],
data_to_insert["test_results"],
data_to_insert["err_code"],
data_to_insert["err_reason"]
))
# 변경사항 저장
connection.commit()
5. data insert가 완료되었다면 연결을 해제해 줍니다.
def disconnect_db(connection, cursor):
cursor.close()
connection.close()
728x90
'Study > postgresql' 카테고리의 다른 글
postgresql 설치와 설정 (install & setting) for Mac (1) | 2024.01.25 |
---|
댓글