|
@@ -0,0 +1,56 @@
|
|
1
|
+import psycopg2 as pg
|
|
2
|
+from configparser import ConfigParser
|
|
3
|
+import pandas.io.sql as psql
|
|
4
|
+
|
|
5
|
+def config(filename='database.ini', section='postgresql'):
|
|
6
|
+ """Config parser from http://www.postgresqltutorial.com/postgresql-python/connect/"""
|
|
7
|
+ # create a parser
|
|
8
|
+ parser = ConfigParser()
|
|
9
|
+ # read config file
|
|
10
|
+ parser.read(filename)
|
|
11
|
+
|
|
12
|
+ # get section, default to postgresql
|
|
13
|
+ db = {}
|
|
14
|
+ if parser.has_section(section):
|
|
15
|
+ params = parser.items(section)
|
|
16
|
+ for param in params:
|
|
17
|
+ db[param[0]] = param[1]
|
|
18
|
+ else:
|
|
19
|
+ raise Exception('Section {0} not found in the {1} file'.format(section, filename))
|
|
20
|
+
|
|
21
|
+ return db
|
|
22
|
+
|
|
23
|
+def getQuery(query, qparams = []):
|
|
24
|
+ """
|
|
25
|
+ Get single query
|
|
26
|
+ """
|
|
27
|
+ conn = False
|
|
28
|
+
|
|
29
|
+ try:
|
|
30
|
+ params = config()
|
|
31
|
+
|
|
32
|
+ print("Connecting to database")
|
|
33
|
+
|
|
34
|
+ conn = pg.connect(**params)
|
|
35
|
+ cur = conn.cursor()
|
|
36
|
+
|
|
37
|
+ # Get table
|
|
38
|
+ dataframe = psql.read_sql(query, conn, params = qparams)
|
|
39
|
+
|
|
40
|
+ cur.close()
|
|
41
|
+
|
|
42
|
+ return dataframe
|
|
43
|
+
|
|
44
|
+ except (Exception, pg.DatabaseError) as error:
|
|
45
|
+ print(error)
|
|
46
|
+ return None
|
|
47
|
+
|
|
48
|
+ finally:
|
|
49
|
+ if conn is not False:
|
|
50
|
+ conn.close()
|
|
51
|
+ print('Database connection closed')
|
|
52
|
+
|
|
53
|
+if __name__ == "__main__":
|
|
54
|
+ dv = getQuery('SELECT version()').version[0]
|
|
55
|
+ print('PostgreSQL database version:')
|
|
56
|
+ print(dv)
|