forked from ElenaMLambert/dtsa5714
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
102 lines (77 loc) · 2.34 KB
/
db.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
from os import environ as env
from dotenv import load_dotenv
import psycopg2
from psycopg2 import DatabaseError
load_dotenv()
DATABASE_URL = env['DB_URL']
CONN = None # cached connection
def get_connection():
global CONN
if CONN and not CONN.closed:
return CONN
conn = None
try:
conn = psycopg2.connect(DATABASE_URL)#, sslmode='require')
conn.autocommit = True
print(conn)
except (Exception, DatabaseError) as error:
print(error)
return
CONN = conn
return CONN
def execute(sql):
conn = get_connection()
with conn.cursor() as cur:
try:
cur.execute(sql)
except (Exception, DatabaseError) as error:
print(error)
#conn.close()
def init():
fn = open(f'./src/schema/schema.sql', 'r')
sql = fn.read()
fn.close()
execute(sql)
def close():
if CONN:
CONN.close()
def insert_record(r):
try:
sql = "insert into trades (docId, firstName, lastName, filingType, stateDst, year, filingDate, trades) values('{}','{}','{}','{}','{}','{}','{}','{}')".format(
r['docId'],
r['firstName'],
r['lastName'],
r['filingType'],
r['stateDst'],
r['year'],
r['filingDate'],
r['trades']
)
execute(sql)
except (Exception, DatabaseError) as error:
print(error)
def read_records(columns, tablename='trades', filter=None, orderBy=None):
try:
sql = f"select {','.join(columns)} from {tablename}"
if filter:
sql = sql + f' where {filter}'
if orderBy:
sql = sql + f' order by {orderBy} desc'
conn = get_connection()
with conn.cursor() as cur:
cur.execute(sql)
records = cur.fetchmany(2000)
return records
except (Exception, DatabaseError) as error:
print(error)
def remove_records(filter=None, tablename='trades'):
try:
sql = f"delete from {tablename}"
if filter:
sql = sql + f' where {filter}'
conn = get_connection()
with conn.cursor() as cur:
cur.execute(sql)
print(f'executing {sql}')
except (Exception, DatabaseError) as error:
print(error)