added more error handling and explicit opening and closing of connections