-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresClient.py
44 lines (37 loc) · 1.43 KB
/
postgresClient.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
import psycopg2
import psycopg2.extras as extras
import configParser as config
def connect(conf, section):
try:
conn = psycopg2.connect(database=config.fetch(key='name', file=conf, section=section),
host=config.fetch(key='localhost', file=conf, section=section),
port=config.fetch(key='port', file=conf, section=section),
user=config.fetch(key='user', file=conf, section=section),
password=config.fetch(key='password', file=conf, section=section), cursor_factory=extras.DictCursor)
return conn
except:
print "Connection error, please check your connection settings"
raise
def close(connection):
try:
connection.cursor().close()
connection.close()
except:
print "Connection not closed!"
raise
def readTable(table, columns, conf, section):
results = []
try:
conn = connect(conf=conf, section=section)
cur = conn.cursor()
cur.execute("SELECT {} FROM {}".format(", ".join(columns), table))
for val in cur.fetchall():
results.append({val[0][:len(val[0])].lower().replace(" ", ""): dict(val)})
close(conn)
if results is not None:
return results
except:
print "No results were returned"
raise
if __name__ == "__main__":
readTable('users', ['email', 'name'])