在asp.net应用程序中打开/关闭连接的好习惯? [英] Good practice to open/close connections in an asp.net application?
问题描述
我一直在ASP.net中开发一个Web应用程序.我的应用程序有几个页面,所有页面都需要显示数据库填充的表.现在,我正在做的是在每个页面上打开数据库连接,执行特定于该页面的查询,并关闭数据库连接.因此,每次用户单击链接进入新页面或单击表格控件(例如网格页面)时,都会发生这种情况.
I've been working on a web application in ASP.net. My application has several pages and all of them need to display tables that are populated by a database. Right now what I'm doing is, on each page, I'm opening a database connection, executing the query specific to that page, and closing the db connection. So this happens each time the user clicks a link to go to a new page or clicks a form control like the grid page.
从性能的角度来看,我想知道这是否是一场灾难.有什么更好的方法吗?
I was wondering if this was a disaster from the performance point of view. Is there any better way to do this?
推荐答案
几乎普遍,数据库连接应按以下方式处理:尽可能晚打开,并尽快关闭.打开和关闭多个查询/更新...不要以为打开会为您节省任何费用.因为连接池通常对您管理连接非常好.
Almost universally, database connections should be handled as follows: Open as late as possible, and close as soon as possible. Open and close for multiple queries/updates... don't think leaving it open saves you anything. Because connection pooling generally does a very good job for you of managing the connections.
在单个页面的生产中打开/关闭几个/几个连接是非常好的.试图保持页面视图之间的单个连接打开很不好,在任何情况下都不要这样做.
It is perfectly fine to have a couple/few connections opened/closed in the production of a single page. Trying to keep a single connection open between page views would be quite bad... don't do that under any circumstances.
基本上,对于连接池(几乎所有提供程序都默认启用),实际上关闭"连接只是将其释放回池中以供重用.尝试自己打开它会占用宝贵的联系.
Basically, with connection pooling (enabled by default for almost all providers), "closing" a connection actually just releases it back to the pool to be reused. Trying to keep it open yourself will tie up valuable connections.
这篇关于在asp.net应用程序中打开/关闭连接的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!