Use the Dbutils POOLEDDB connection pool to manipulate the database.
This makes it unnecessary to close the database connection after each SQL execution, creating connections frequently and consuming time
If you are using a connection that has not been shut down for a long time after running under multiple threads it is easy to appear operationalerror: (2006, ' MySQL server has gone away ') this error.
Use POOLEDDB to resolve.
#Coding=utf-8"""using connections from the Dbutils database connection pool, manipulate database Operationalerror: (2006, ' MySQL server has gone away ')"""ImportJSONImportPymysqlImportdatetime fromDbutils.pooleddbImportPOOLEDDBImportPymysqlclassmysqlclient (object):__pool=None; def __init__(Self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, Maxusage=100, Setsession=none, reset=True, Host='127.0.0.1', port=3306, db='Test', the user='Root', passwd='123456', charset='UTF8MB4'): if notSelf.__pool: Self.__class__.__pool=pooleddb (Pymysql, mincached, maxcached, Maxshared, MaxConnections, blocking, Maxusage, setsession, Reset, Host=host, Port=port, db=db, User=user, passwd=passwd, CharSet=CharSet, Cursorclass=pymysql.cursors.DictCursor) Self._conn=None self._cursor=None self.__get_conn() def __get_conn(self): Self._conn= self.__pool. Connection (); Self._cursor=self._conn.cursor (); def __close(self):Try: Self.cursor.close () self.conn.close ()exceptException as E:Printedef __execute(Self, SQL, param=()): Count=self._cursor.execute (sql, param)PrintCountreturnCount @staticmethoddef __dict_datetime_obj_to_str(result_dict):"""convert the Datatime object in the dictionary to a string so that the JSON conversion does not go wrong""" ifResult_dict:result_replace= {K:v.__str__() forKvinchResult_dict.items ()ifisinstance (V, Datetime.datetime)} result_dict.update (Result_replace)returnresult_dictdefSelect_one (self, SQL, param=()): """Querying single results"""Count= self.__execute(SQL, param) result=Self._cursor.fetchone ()""": Type result:dict"""result= self.__dict_datetime_obj_to_str(Result)returncount, resultdefSelect_many (self, SQL, param=()): """querying multiple results:p Aram SQL:QSL statement:p Aram Param:sql parameter: Return: Result quantity and query result set"""Count= self.__execute(SQL, param) result=Self._cursor.fetchall ()""": Type Result:list"""[self.__dict_datetime_obj_to_str(row_dict) forRow_dictinchresult]returncount, resultdefExecute (Self, SQL, param): Count= self.__execute(SQL, param)returnCountdefbegin (self):"""Open Transaction"""self._conn.autocommit (0)defEnd (self, option='Commit'): """End Transaction""" ifoption = ='Commit': Self._conn.autocommit ()Else: Self._conn.rollback ()if __name__=="__main__": MC=mysqlclient () sql1='SELECT * from Shijiji WHERE id = 1'RESULT1=Mc.select_one (SQL1)PrintJson.dumps (result1[1], ensure_ascii=False) Sql2='SELECT * from Shijiji WHERE ID in (%s,%s,%s)'param= (2, 3, 4) PrintJson.dumps (Mc.select_many (SQL2, param) [1], Ensure_ascii=false)
Operate the database using the Dbutils POOLEDDB connection pool