Repository for Petra's work at ampli Jan-Feb 2019

dbtest.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import psycopg2 as pg
  2. from configparser import ConfigParser
  3. import pandas.io.sql as psql
  4. def config(filename='database.ini', section='postgresql'):
  5. """Config parser from http://www.postgresqltutorial.com/postgresql-python/connect/"""
  6. # create a parser
  7. parser = ConfigParser()
  8. # read config file
  9. parser.read(filename)
  10. # get section, default to postgresql
  11. db = {}
  12. if parser.has_section(section):
  13. params = parser.items(section)
  14. for param in params:
  15. db[param[0]] = param[1]
  16. else:
  17. raise Exception('Section {0} not found in the {1} file'.format(section, filename))
  18. return db
  19. conn = False
  20. try:
  21. params = config()
  22. print("Connecting to database")
  23. conn = pg.connect(**params)
  24. cur = conn.cursor()
  25. print('PostgreSQL database version')
  26. cur.execute('SELECT version()')
  27. db_version = cur.fetchone()
  28. print(db_version)
  29. # Get tables
  30. dataframe = psql.read_sql("SELECT * FROM pg_catalog.pg_tables", conn)
  31. # Too big!
  32. # dataframe = psql.read_sql("SELECT * FROM coup_prd.coupdata_2016_06", conn)
  33. print(dataframe)
  34. cur.close()
  35. except (Exception, pg.DatabaseError) as error:
  36. print(error)
  37. finally:
  38. if conn is not False:
  39. conn.close()
  40. print('Database connection closed')