123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import psycopg2 as pg
- from configparser import ConfigParser
- import pandas.io.sql as psql
-
-
- def config(filename='database.ini', section='postgresql'):
- """Config parser from
- http://www.postgresqltutorial.com/postgresql-python/connect/"""
- # create a parser
- parser = ConfigParser()
- # read config file
- parser.read(filename)
-
- # get section, default to postgresql
- db = {}
- if parser.has_section(section):
- params = parser.items(section)
- for param in params:
- db[param[0]] = param[1]
- else:
- raise Exception(
- 'Section {0} not found in the {1} file'.format(section, filename))
-
- return db
-
-
- def getQuery(query, qparams=[]):
- """
- Get single query
- """
- conn = False
-
- try:
- params = config()
-
- print("Connecting to database")
-
- conn = pg.connect(**params)
- cur = conn.cursor()
-
- # Get table
- dataframe = psql.read_sql(query, conn, params=qparams)
-
- cur.close()
-
- print("Table recieved")
-
- return dataframe
-
- except (Exception, pg.DatabaseError) as error:
- print(error)
- return None
-
- finally:
- if conn is not False:
- conn.close()
- print('Database connection closed')
-
-
- def pickleQuery(query, path, qparams=[]):
- dq = getQuery(query, qparams)
- dq.to_pickle(path)
- print("Table pickled")
-
-
- if __name__ == "__main__":
- dv = getQuery('SELECT version()').version[0]
- print('PostgreSQL database version:')
- print(dv)
|