Remove duplicate code

Removed the get database code in every function and put it at the top.