baoshiwei
2026-03-13 6628f663b636675bcaea316f2deaddf337de480e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import psycopg2
from psycopg2 import OperationalError
from dotenv import load_dotenv
 
# 加载环境变量
load_dotenv()
 
class DatabaseConnection:
    def __init__(self):
        self.host = os.getenv('DB_HOST')
        self.port = os.getenv('DB_PORT')
        self.database = os.getenv('DB_NAME')
        self.user = os.getenv('DB_USER')
        self.password = os.getenv('DB_PASSWORD')
        self.connection = None
    
    def connect(self):
        try:
            self.connection = psycopg2.connect(
                host=self.host,
                port=self.port,
                database=self.database,
                user=self.user,
                password=self.password
            )
 
            
            with self.connection.cursor() as cursor:
                cursor.execute("SET timezone = 'UTC'")
            return True
        except OperationalError as e:
            print(f"数据库连接失败: {e}")
            return False
    
    def disconnect(self):
        if self.connection:
            self.connection.close()
            self.connection = None
    
    def get_connection(self):
        if not self.connection:
            if not self.connect():
                return None
        return self.connection
    
    def is_connected(self):
        if not self.connection:
            return False
        try:
            # 执行一个简单的查询来测试连接
            with self.connection.cursor() as cursor:
                cursor.execute("SELECT 1")
                cursor.fetchone()
            return True
        except:
            return False