Refactor out the database connnection logic