Reconnecting to the database only if necessary