Files
FACULTATE-MESSENGER/messenger_app/api/v1/database/postgres_database.py
T
2024-01-09 03:06:03 +02:00

39 lines
1004 B
Python

import psycopg2
DATABASE_CONFIG = {
'dbname': 'messenger',
'user': 'andrei_cerbu',
'password': 'andrei',
'host': 'localhost',
'port': '5432'
}
def create_connection():
try:
connection = psycopg2.connect(**DATABASE_CONFIG)
return connection
except psycopg2.Error as e:
print(f"Error: Unable to connect to the database\n{e}")
return None
def execute_query(connection, query, params=None, fetchall=False):
try:
with connection.cursor() as cursor:
cursor.execute(query, params)
if fetchall:
result = cursor.fetchall()
return result
else:
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_connection(connection):
if connection:
connection.close()
print("Connection closed.")