Added check if database is connected before trying to close it.