Refactory to fix problem of unclosed database connection