Properly closes the database connection before ending a thread.