-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbconnector.py
71 lines (55 loc) · 1.66 KB
/
dbconnector.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
import psycopg2
import sys
class DBConnector:
connector = None
def __init__(self):
self.conn = None
self.dbuser = None
self.dbpassword = None
self.dbhost = None
self.dbname = None
@staticmethod
def get_connection():
if DBConnector.connector == None:
DBConnector.connector = DBConnector()
DBConnector.connector.connect()
return DBConnector.connector
def read_conn_info(self):
conn_info = dict()
try:
fo = open("conn-info.txt", "r")
for line in fo:
key_value = line.split('=',1)
if len(key_value) == 2:
conn_info[key_value[0].lstrip().rstrip()] = key_value[1].lstrip().rstrip()
except IOError, e:
print e
return conn_info
def connect(self):
conn_info = self.read_conn_info()
try:
self.dbname = conn_info['dbname']
self.dbuser = conn_info['user']
self.dbpassword = conn_info['password']
self.dbhost = conn_info['host']
self.conn = psycopg2.connect(database=self.dbname,user=self.dbuser,host=self.dbhost,password=self.dbpassword)
except:
print sys.exc_info()[0]
print "Unable to connect to the Database. Please check DB configuration in file conn-info.txt"
'''def connect_db(self, dbname):
self.dbname = dbname
if self.dbuser is None:
print "No user name for connection"
return
elif self.dbpassword is None:
print "No password for connection"
return
elif self.dbhost is None:
print "No host for connection"
return
try:
self.conn = psycopg2.connect(user=self.dbuser,host=self.dbhost,password=self.dbpassword,database=self.dbname)
except:
print sys.exc_info()[0]
print "Unable to connect to the Database. Please check DB configuration in file conn-info.txt"
'''