Changed database connection strategy. Now a connection is opened only when needed, and closed when querying is done. This should eliminate "OperationalError 2006, 'MySQL server has gone away'" error.

Opening connections is fairly cheap according to http://stackoverflow.com/questions/14883346/how-should-i-establish-and-manage-database-connections-in-a-multi-module-python