What's the right way to retry when connection/write to a DB fails in python?
I'm trying to use this code and it works until i restart my sql server and python tries to connect to it i get "retry after 30 sec" for 10 times with 30 secs intervals but it won't reconnect when sql server is running again.
EDIT: It reconnects when retry_count1 = 10 but at next cycle counter needs to count up to 10 before it connects again.
Does anyone have a idea why it wont reconnect?
retry_flag1 = True
retry_count1 = 0
while retry_flag1 and retry_count1 < 10:
try:
cursor = cnxn.cursor()
cursor.execute('SELECT too_id FROM [TTMM].[dbo].[Machines] WHERE MachineID = {}'.format (machineid,))
too_id = cursor.fetchone()[0]
cursor.execute('INSERT INTO [TTMM].[dbo].[{}](counter, effectively, too_id) VALUES ({},{},{})'.format (machineid, counter, effectively, too_id,))
cnxn.commit()
cursor.close()
retry_flag1 = False
except as e:
print(e)
print("Retry after 30 sec")
retry_count1 = retry_count1 + 1
time.sleep(30)
Here's the console output after restarting sql server.
('08S01', '[08S01] [FreeTDS][SQL Server]Write to the server failed (20006) (SQLExecDirectW)')
Retry after 1 sec
('08S01', '[08S01] [FreeTDS][SQL Server]Communication link failure (0) (SQLExecDirectW)')
Retry after 1 sec
('08S01', '[08S01] [FreeTDS][SQL Server]Communication link failure (0) (SQLExecDirectW)')
Retry after 1 sec
141222 Cykel
('08S01', '[08S01] [FreeTDS][SQL Server]Communication link failure (0) (SQLExecDirectW)')
Retry after 1 sec
('08S01', '[08S01] [FreeTDS][SQL Server]Communication link failure (0) (SQLExecDirectW)')
except, catch the specific connection related exception.excepttoexcept Exception as e:and then printe. That will give you the error that is being thrown. Update your question with that information, and it will be easier to give you input on the actual error. Find more information here: stackoverflow.com/questions/18982610/…