fill_database: commit when needed and close cursor