Skip to content

Instantly share code, notes, and snippets.

@elena-roff
Created October 8, 2019 13:55
Show Gist options
  • Save elena-roff/5bae7901ee4e0c117e48a0feda9de712 to your computer and use it in GitHub Desktop.
Save elena-roff/5bae7901ee4e0c117e48a0feda9de712 to your computer and use it in GitHub Desktop.
database setup + query runner
import psycopg2
import psycopg2.extras
from configparser import ConfigParser
import logging
logger = logging.getLogger()
logging.basicConfig(format='%(asctime)s %(message)s')
logger.setLevel(logging.DEBUG)
class Database:
""" DB Setup. """
def __init__(self, connection=None):
self.connection = None
def configure(self, filename:str ='database.ini'):
""" Set configuration for the PostgreSQL database."""
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
config = {}
params = parser.items('postgresql')
for param in params:
config[param[0]] = param[1]
return config
def get_connection(self):
""" Connect to the PostgreSQL database server."""
try:
# read connection parameters
params = self.configure()
# connect to the PostgreSQL server
logger.info('Connecting to the PostgreSQL database.')
self.connection = psycopg2.connect(**params)
except (Exception, psycopg2.DatabaseError) as error:
logger.error(error)
return self.connection
def close_connection(self):
""" Close the connection."""
if self.connection:
self.connection.close()
self.connection = None
class SQLQuery:
def __init__(self, db=None):
self.db = Database()
self.connection = self.db.get_connection()
def run(self, sql_query):
""" Run a given query establishing the PostgreSQL database."""
cur = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
rows = cur.execute(sql_query).fetchall()
cur.close()
return rows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment