Refactor db code to avoid use of cursor objects and look cleaner