Added better handling of SQL errors and made changes to allow these to be tested
Cosmetic changes/comments added