Unless there are special circumstances, it's almost always connect only when needed. There are several advantages:
- Resources are held for the shortest time possible, thus maximising their availability.
- The lifetime scope of connections is controlled at a single point in code, minimising the chance of resource leaks.
- Data is written frequently, thus minimising loss of data due to crashes.
- Retry logic is simpler, since connection state is localised to a single point in code
In general: Open connections as late as possible, as briefly as is possible, and close as quickly as possible
(Many database systems implement connection pooling which makes this process very efficient)