Bug fixes and fix a memory leak

1) only try to remove the temporary directory of it was created, 2)
free memory of “globals”.
Adding a sanity check

Only disconnect from a DB if the handle is connected (!= NULL).
Otherwise, it may cause segmentation fault on some version of SQLite.