- Setting a Timeout: You can specify "LoginTimeout" while establishing connection to the database. It specifies the number of seconds that the driver waits while trying to connect to a database before throwing an error. Refer to the "Name-Value Arguments" section of this link for more details.
- Using try/catch: You can wrap your SQL pull in a try/catch block to handle any errors and retry the operation if it fails.
SQL freezes or fails randomly, how to timeout or try/catch?
3 views (last 30 days)
Show older comments
Hi,
I have a function that only has an sql pull in it. Sometimes it works, sometimes it doesnt. In another function that calles the sql pulls, if it is run together, it fails. If it stops right before and I run the function by putting it in the workspace, it works. Sometimes it crashes matlab. When it fails, it usually holds for a long time. Normally it should only take about 2 seconds when it does work. Is there a timeout function I can use to break matlab away from it when it freezes on the sql pull? How could I used a try/catch statement to catch it and make it try it again if it doesnt work?
0 Comments
Answers (1)
Piyush Kumar
on 22 Oct 2024
Hi,
To handle SQL freezes or failures in MATLAB, you can use a combination of try/catch blocks and setting a timeout for your database connection.
maxRetries = n; % Maximum number of retries
retryCount = 0;
success = false;
% Define sql query
while ~success && retryCount < maxRetries
try
% Execute SQL query
curs = exec(conn, sqlquery);
success = true; % If query is successful, set success to true
catch ME
% If an error occurs, increment retry count and display error message
retryCount = retryCount + 1;
disp(['Attempt ' num2str(retryCount) ' failed: ' ME.message]);
pause(2); % Pause for 2 seconds before retrying
end
end
if ~success
error('Failed to execute SQL query after multiple attempts.');
end
0 Comments
See Also
Categories
Find more on Database Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!