Advertisement
mbratanov

Database Connection

Feb 19th, 2025
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. import psycopg2
  2.  
  3. class PostgreSQLConnection:
  4.     def __init__(self, host, port, database, user, password):
  5.         self.host = host
  6.         self.port = port
  7.         self.database = database
  8.         self.user = user
  9.         self.password = password
  10.         self.connection = None
  11.  
  12.     def connect(self):
  13.         if self.connection is None:
  14.             self.connection = psycopg2.connect(
  15.                 host=self.host,
  16.                 port=self.port,
  17.                 database=self.database,
  18.                 user=self.user,
  19.                 password=self.password
  20.             )
  21.  
  22.     def close(self):
  23.         if self.connection:
  24.             self.connection.close()
  25.             self.connection = None
  26.  
  27.     def __enter__(self):
  28.         self.connect()
  29.         return self.connection
  30.  
  31.     def __exit__(self, exc_type, exc_val, exc_tb):
  32.         self.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement