Use standard transaction pattern

This catches exceptions and makes sure that transactions are committed or rolled back.