Replace connection code with Query instances.

Remove duplicated code, and replace with the query builder.