Reworked database connection logic to make sure db connections get closed