Fixes bug in closing database connections