Move the connection outside the loop