Skip to content

Instantly share code, notes, and snippets.

@embray
Last active August 26, 2021 15:42
Show Gist options
  • Save embray/a3e05926c4b3127a594b871eabe75262 to your computer and use it in GitHub Desktop.
Save embray/a3e05926c4b3127a594b871eabe75262 to your computer and use it in GitHub Desktop.
class DatabaseWrapper:
def __init__(self, params=None):
if params is None:
# read connection params from a config file (?)
params = self.config()
self.connection_params = params
self.connection = None
def config(self):
"""Reads database config from...somewhere."""
def connect(self):
"""Creates a database connection--if already connected this is a no-op."""
if self.connection is not None:
return
self.connection = psycopg.connect(**self.connection_params)
def disconnect(self):
if self.connection is not None:
self.connection.close()
self.connection = None
def execute_sql(self, sql_statement):
"""Execute a SQL query."""
` `
self.connect()
with self.connection:
# Using the connection in a context manager guarantees clean rollback
# on error, and commit on successful transactions
# You don't need the 'mode' argument from your version.
with conn.cursor() as cur:
cur.execute(sql_statement)
# If this was a SELECT this will return all the results (dangerous for
# large queries, avoid this if possible). Otherwise psycopg raises a
# ProgrammingError but we can just return None
try:
return cur.fetchall()
except psycopg.ProgrammingError:
# Query did not return anything
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment