-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgresDatabase.py
More file actions
43 lines (43 loc) · 1.48 KB
/
Copy pathPostgresDatabase.py
File metadata and controls
43 lines (43 loc) · 1.48 KB
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
import psycopg2
class PostgresDatabase:
def __init__(self):
self.host =
self.port =
self.dbname =
self.user =
self.password =
self.connection = None
self.cursor = None
def connect(self):
try:
self.connection = psycopg2.connect(
host=self.host,
port=self.port,
dbname=self.dbname,
user=self.user,
password=self.password
)
self.cursor = self.connection.cursor()
except Exception as e:
print("Error connecting to PostgreSQL:", e)
def execute_query(self, query, params=None):
try:
self.cursor.execute(query, params)
self.column_names = [desc[0] for desc in self.cursor.description]
return self.cursor.fetchall() , self.column_names
except Exception as e:
print("Error executing query:", e)
return None
def execute_non_query(self, query, params=None):
try:
self.cursor.execute(query, params)
self.connection.commit()
except Exception as e:
if str(type(e)) == "<class 'psycopg2.errors.UniqueViolation'>":
self.connection.rollback()
return 'Username Exists'
def close(self):
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()