SQLite: free memory, improve error handling, check integrity