When using databases, I would always connect at the very first of the script, just to ensure there are no leaks.