Reuse database connection code.

This will also make it easier to add unit tests as a dummy Connection object can be inserted.