This commit is contained in:
andrei-mihnea-cerbu
2024-01-12 22:19:19 +02:00
parent 37b2c068b8
commit e65b05b451
59 changed files with 349 additions and 190 deletions
@@ -0,0 +1,4 @@
from .connection import POSTGRESQL_CONFIG, PostgreSQLHandler
postgresql_db_handler = PostgreSQLHandler(**POSTGRESQL_CONFIG)
postgresql_db_handler.connect()
@@ -0,0 +1,54 @@
import psycopg2
class PostgreSQLHandler:
def __init__(self, dbname, user, password, host, port):
self.dbname = dbname
self.user = user
self.password = password
self.host = host
self.port = port
self.connection = None
def connect(self):
try:
self.connection = psycopg2.connect(
dbname=self.dbname,
user=self.user,
password=self.password,
host=self.host,
port=self.port
)
print("Connected to PostgreSQL.")
return self.connection
except psycopg2.Error as e:
print(f"Error: Unable to connect to the PostgreSQL database\n{e}")
return None
def execute_query(self, query, params=None, fetchall=False):
try:
with self.connection.cursor() as cursor:
cursor.execute(query, params)
if fetchall:
result = cursor.fetchall()
return result
else:
self.connection.commit() # Commit the transaction for INSERT, UPDATE, DELETE queries
except psycopg2.Error as e:
print(f"Error: Unable to execute the query\n{e}")
return None
def close(self):
if self.connection:
self.connection.close()
print("PostgreSQL connection closed.")
self.connection = None
POSTGRESQL_CONFIG = {
'dbname': 'vliwybbf',
'user': 'vliwybbf',
'password': 'X0fhZ6NT3mjT7rbgZ5lQQ6ZYQpVyUwxq',
'host': 'rogue.db.elephantsql.com',
'port': '5432'
}