Speed up database operations

1. Prepare statements only once.
2. Use batched inserts.