Refactor the database code to reduce the duplicated code