Refactor database connection functios