Write/saved logs in WordPress

I’d recommend doing large bulk updates to the database like big imports or exports outside of the WordPress codebase as much as possible because of issues like this, but only if this makes sense for your code and you’re able to maintain the wordpress data structures

If the logging information is just to see what happens with this operation and you don’t need it after or to see it in WordPress, then update_option is definitely not a great solution. Opening a file, or writing to your own table would be better.

There’s no reason not to write a PHP script which opens a single connection to the database to do its work, a single file for logging and does what it needs to do.

Or, if you want to take advantage of some WordPress calls, then use wp-cli’s eval-file to run a script which will give you access to those.

For tasks like this if you don’t already have it then access to the command line, e.g. through ssh will make your life a lot easier and save you tons of time. This approach may also give you much easier access to error messages.

For more help with the specific thing you’re doing more details on the heavy query you’re running would help. Connection refused and those other errors could be caused by a lot of things, but your approach of having logging somewhere is a good one, as long as it helps to diagnose problems and retry the rest of the work.