This repository has been archived by the owner on Nov 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
dblib.py
76 lines (66 loc) · 2.02 KB
/
dblib.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
# -*- coding: utf-8 -*-
from psycopg2 import connect
from psycopg2.extensions import register_type, UNICODE
from psycopg2.extras import DictConnection
class DbConnection(object):
def __init__(self, dbname, user=None, pswd=None, host=None, port=None):
self.dbname = dbname
if user is None:
self.user = ''
else:
self.user = " user=%s" % user
if pswd is None:
self.pswd = ''
else:
self.pswd = " password=%s" % pswd
if host is None or host == '127.0.0.1' or host == 'localhost':
self.host = ''
else:
self.host = "host=%s " % host
if port is None or port == 5432:
self.port = ''
else:
self.port = "port=%d " % port
self.conn = None
def connect(self):
register_type(UNICODE)
dsn = '%s%sdbname=%s%s%s' % (self.host, self.port, self.dbname,
self.user, self.pswd)
try:
self.conn = connect(dsn, connection_factory=DictConnection)
except Exception as exc:
raise exc
def close(self):
if self.conn:
self.conn.close()
def commit(self):
self.conn.commit()
def rollback(self):
self.conn.rollback()
def fetchall(self, query):
try:
curs = self.execute(query)
except Exception as exc:
raise exc
rows = curs.fetchall()
curs.close()
return rows
def fetchone(self, query, args=None):
try:
curs = self.execute(query, args)
except Exception as exc:
raise exc
row = curs.fetchone()
curs.close()
return row
def execute(self, query, args=None):
if self.conn is None:
self.connect()
curs = self.conn.cursor()
try:
curs.execute(query, args)
except Exception as exc:
self.conn.rollback()
curs.close()
raise exc
return curs