Finished code for thread-safe database interface