Open and close DB and cursor only as needed