使用“最后尝试”的数据库连接
有人可以启发我如何使用 try finally 处理数据库连接(和错误)吗? 最好的做法是什么? 见过各种风格,但我想知道什么是最好的方法。 表的打开应该放在 TRY 块中还是仅仅放在主连接中 细绳 ? 因为我通常将我的数据库(绝对数据库,access..)放在我的exe文件夹中 我想知道这方面的最佳方法...... 或者首先检查文件,例如...
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;
???
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;
???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注释:
ShowMessage
案例中所做的那样。调用您的过程的代码无法知道出了什么问题。仅在可以修复错误时才处理错误,或者让它们在应用程序错误处理程序中冒泡,并在其中向用户显示错误。try-finally
保护与数据库的连接,以便在作业完成后断开连接。我不这样做,我通常在应用程序的生命周期内保持连接打开。try-finally
块一起使用完它后将其关闭。我通常这样做是因为我不使用 Db 感知的 GUI 控件,而且我是一个控制狂。我也手动处理事务(启动事务/提交/回滚)FileExists()
返回 false),则调用您的过程的代码不知道任何事情,用户也不知道。这是我重写你的代码的方式:
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 othertry-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 I cannot open the database I terminate the application - not much you can do without database access unless you specifically build an architecture that handles this.
Other than this, just let the default application error handler handle the error, since it would be pretty unexpected anyway.