Skip to content

Commit 705d8fd

Browse files
Clickhouse 연결을 위한 py 파일 생성
1 parent 719c8c9 commit 705d8fd

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

llm_utils/connect_db.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import os
2+
from typing import Union
3+
import pandas as pd
4+
from clickhouse_driver import Client
5+
from dotenv import load_dotenv
6+
7+
# 환경변수
8+
load_dotenv()
9+
10+
11+
class ConnectDB:
12+
def __init__(self):
13+
self.client = None
14+
self.host = os.getenv("CLICKHOUSE_HOST")
15+
self.dbname = os.getenv("CLICKHOUSE_DATABASE")
16+
self.user = os.getenv("CLICKHOUSE_USER")
17+
self.password = os.getenv("CLICKHOUSE_PASSWORD")
18+
self.port = os.getenv("CLICKHOUSE_PORT")
19+
20+
def connect_to_clickhouse(self):
21+
22+
# ClickHouse 서버 정보
23+
self.client = Client(
24+
host=self.host,
25+
port=self.port,
26+
user=self.user,
27+
password=self.password,
28+
database=self.dbname, # 예: '127.0.0.1' # 기본 TCP 포트
29+
)
30+
31+
def run_sql(self, sql: str) -> Union[pd.DataFrame, None]:
32+
if self.client:
33+
try:
34+
result = self.client.execute(sql, with_column_types=True)
35+
# 결과와 컬럼 정보 분리
36+
rows, columns = result
37+
column_names = [col[0] for col in columns]
38+
39+
# Create a pandas dataframe from the results
40+
df = pd.DataFrame(rows, columns=column_names)
41+
return df
42+
43+
except Exception as e:
44+
raise e

0 commit comments

Comments
 (0)