Ensure cursor is closed before attempting to close connection