Moved the query execution code into a function.