Refactored query connection selection.