Last active
August 26, 2021 15:42
-
-
Save embray/a3e05926c4b3127a594b871eabe75262 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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