k_db.py 2.2 KB
Newer Older
1 2
import psycopg2

陈正乐 committed
3

4
class PostgresDB:
陈正乐 committed
5
    """
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    psycopg2.connect(
        dsn         #指定连接参数。可以使用参数形式或 DSN 形式指定。
        host        #指定连接数据库的主机名。
        dbname      #指定数据库名。
        user        #指定连接数据库使用的用户名。
        password    #指定连接数据库使用的密码。
        port        #指定连接数据库的端口号。
        connection_factory  #指定创建连接对象的工厂类。
        cursor_factory      #指定创建游标对象的工厂类。
        async_      #指定是否异步连接(默认False)。
        sslmode     #指定 SSL 模式。
        sslrootcert #指定证书文件名。
        sslkey      #指定私钥文件名。
        sslcert     #指定公钥文件名。
    )
陈正乐 committed
21 22 23
    """

    def __init__(self, host, database, user, password, port=5432):
24 25 26 27 28 29 30 31 32
        self.host = host
        self.database = database
        self.user = user
        self.password = password
        self.port = port
        self.conn = None
        self.cur = None

    def connect(self):
陈正乐 committed
33
        self.conn = psycopg2.connect(
34 35 36 37
            host=self.host,
            database=self.database,
            user=self.user,
            password=self.password,
陈正乐 committed
38
            port=self.port
39 40 41 42 43
        )
        self.cur = self.conn.cursor()

    def execute(self, query):
        try:
陈正乐 committed
44 45 46 47
            self.cur.execute(query)
            self.conn.commit()
        except Exception as e:
            print(f"An error occurred: {e}")
48
            self.conn.rollback()
陈正乐 committed
49

50 51
    def execute_args(self, query, args):
        try:
陈正乐 committed
52 53 54 55
            self.cur.execute(query, args)
            self.conn.commit()
        except Exception as e:
            print(f"An error occurred: {e}")
56 57 58 59 60 61 62 63 64 65 66 67 68 69
            self.conn.rollback()

    def search(self, query, params=None):
        self.cur.execute(query, params)

    def fetchall(self):
        return self.cur.fetchall()

    def close(self):
        self.cur.close()
        self.conn.close()

    def format(self, query):
        try:
陈正乐 committed
70 71 72 73
            self.cur.execute(query)
            self.conn.commit()
        except Exception as e:
            print(f"An error occurred: {e}")
74
            self.conn.rollback()