Either you haven't opened the connection yet or you have already closed it.
With the exception of loops and subroutine calls, code executes from top to bottom.
There's no magic.
If you need to do
connection.Exeucte then someplace BEFORE that line you need to create and open a connection *AND* you can't close the connection until AFTER that point. Simple steps. A, B, C, D, etc.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.