-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBOps.py
101 lines (90 loc) · 2.93 KB
/
DBOps.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
import psycopg2
import time
import random
class DBOps:
def __init__(self):
str()
def select_DEP(self, query, onerow=False):
self.cr.execute(query)
records = self.cr.fetchall()
if onerow:
for row in records:
return row
# self.cr.close()
# self.connection.close()
return records
def exec_DEP(self, query):
print(query)
self.__init__()
self.cr.execute(query)
self.connection.commit()
self.cr.close()
self.connection.close()
return self.cr.rowcount
def close(self):
self.cr.close()
self.connection.close()
def select(self, query, onerow=False):
conString = "user=# password=# host=# port=5432 dbname=#"
try:
connection = psycopg2.connect(conString)
cr = connection.cursor()
except (Exception, psycopg2.Error) as error:
print("can't connect DB!", error)
records = None
try:
with connection:
with connection.cursor() as cr:
cr.execute(query)
records = cr.fetchall()
if onerow:
for row in records:
return row
cr.close()
connection.close()
# return records
except:
time.sleep(random.randint(0, 2))
try:
with connection:
with connection.cursor() as cr:
cr.execute(query)
records = cr.fetchall()
if onerow:
for row in records:
return row
cr.close()
connection.close()
# return records
except:
pass
return records
def exec(self, query):
print(query)
conString = "user=# password=# host=# port=5432 dbname=#"
try:
connection = psycopg2.connect(conString)
cr = connection.cursor()
except (Exception, psycopg2.Error) as error:
print("can't connect DB!", error)
# print(query)
try:
with connection:
with connection.cursor() as cr:
cr.execute(query)
cr.close()
# connection.close()
return cr.rowcount
except Exception as e:
print(e)
time.sleep(random.randint(0, 3))
try:
with connection:
with connection.cursor() as cr:
cr.execute(query)
cr.close()
# connection.close()
return cr.rowcount
except Exception as e:
print(e)
pass