-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres1.py
More file actions
58 lines (49 loc) · 2.08 KB
/
postgres1.py
File metadata and controls
58 lines (49 loc) · 2.08 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from datetime import datetime
import psycopg2
class PostgreSql:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = psycopg2.connect(f"host={self.host} port={self.port} user={self.user} password={self.password} dbname={self.database}")
self.conn.autocommit = True
self.cur = self.conn.cursor()
def reconnect(self):
if self.cur:
self.cur.close()
if self.conn:
self.conn.close()
self.conn = psycopg2.connect(f"host={self.host} port={self.port} user={self.user} password={self.password} dbname={self.database}")
self.cur = self.conn.cursor()
def select(self, query, data, retries=3):
for _ in range(retries):
try:
self.cur.execute(query, data)
return self.cur.fetchall()
except psycopg2.InterfaceError:
print("Database connection error")
self.reconnect()
raise psycopg2.InterfaceError("Failed after multiple retries")
def insert(self, data, table):
insert_query = f"INSERT INTO {table} (taskrefId, subject, homework_name, due_date, status, url) VALUES (%s, %s, %s, %s, %s, %s);"
try:
self.cur.execute(insert_query, (data['taskrefId'], data['subject'], data['homework_name'], data['due_date'], data['homework_status'], data['url']))
self.conn.commit()
return True
except Exception as e:
print(f"Insert {data['homework_name']} failed: {e}")
self.conn.rollback()
return False
def update(self, sql, data, retries=3):
for _ in range(retries):
try:
self.cur.execute(sql, data)
self.conn.commit()
except psycopg2.IntegrityError:
print("Update failed due to integrity error")
self.reconnect()
def __del__(self):
self.cur.close()
self.conn.close()