Espero que pueda ayudar:
while True: #it works until the data was not saved
try:
with connection.cursor() as cursor:
print ('saving company details to db')
cursor.execute("""INSERT INTO company(
companyname,address,city,pincode,website)
VALUES (%s, %s, %s, %s, %s)""",
(companyname, companyaddress, companycity,
companypostalcode, companywebsite))
connection.commit()
break
except OperationalError:
connection.ping(True)
print ("Company Data saved")
También puede ver una pregunta similar con el uso de grupo de conexiones
o lea la fuente