Can someone enlighten me on handling the database connection (and errors) using try finally ? What would be the best practice ? Seen various styles but I wonder what would be the best approach. Should opening of the tables be put in TRY block or just the main connection string ? Since I usually put my database (absolute database,access..) in my exe folder I was wondering about the best approach on this... Or first check for file like ...
if (FileExists(sDatabasePath)) then begin
ADOConnection1.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+sDatabasePath+';Persist Security Info=False';
try
ADOConnection1.Connected:=True;
ADOTable1.Open;
except
ShowMessage ('cant access the database !');
end;
end;
???
Comments:
ShowMessage case. The code calling your procedure would have no way of knowing something went wrong. Only handle errors if you can fix them, or let them bubble-up the application error handler, where they'll be displayed for the user.try-finally so you're disconnected once the job is done. I don't do that, I usually keep the connection open for the life of the application.ADOTable1 you might want to make sure it gets closed once you're done using it with an other try-finally block. I usually do that because I don't use Db aware GUI controls and I'm a control-freak. I also handle the transaction manually (start transaction / commit / rollback)FileExists() returns false), code calling your procedure doesn't know a thing, nor does the user.Here's how I'd re-write your code:
if (FileExists(sDatabasePath)) then
begin
ADOConnection1.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+sDatabasePath+';Persist Security Info=False';
ADOConnection1.Connected:=True;
try
ADOTable1.Open;
try
// Do non-GUI database stuff here.
finally ADOTabel1.Close;
end;
finally ADOConnection1.Connected := False;
end;
end
else
raise Exception.Create('Database file not found');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With