我应该使用多少个 SqlConnection 实例

发布于 2024-08-20 09:24:14 字数 327 浏览 4 评论 0原文

背景:
我有一个应用程序,我已经很好地将界面逻辑与处理数据库查询的中间层逻辑分开。我做了很多自定义排序和缩小范围,因此我没有使用很多 SqlDataSource,而是使用 SqlCommand 调用很多存储过程。

我正在使用表单身份验证来创建受保护的子目录。在受保护目录中的 web.config 文件中,我有更多连接字符串,链接到具有更高特权角色的用户。

问题:
我应该在中间层共享一个 SqlConnection 对象来删除重复的代码,还是应该为每个操作创建一个新实例?如果我需要更改连接字符串以访问受保护的存储过程,我可以重新实例化共享的 SqlConnection。这里有最佳实践吗?

Background:
I have an application that I have nicely separated my interface logic from my middle tier logic which handles the queries to the database. I do a lot of custom sorting and narrowing so I'm not using many SqlDataSources and instead calling a lot of stored procedures with SqlCommands.

I am using Forms Authentication to create protected sub-directories. In the web.config files in the protected directories I have more connection strings that link to users with higher privileged roles.

Question:
Should I share a SqlConnection object in my middle tier to cut out repetitive code, or should I create a new instance for each operation? A shared SqlConnection I could re-instantiate if I need to change connection strings to get access to protected stored procedures. Is there a best practice here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软糯酥胸 2024-08-27 09:24:14

不必担心共享以节省资源。 .NET 会为你管理这个,它默认进行连接池。将代码编写得清晰易懂,并让 .NET 处理这些细节。

Don't worry about sharing to conserve resources. .NET will manage this for you, it does connection pooling by default. Write the code to be clear and understandable and let .NET take care of these details.

枫林﹌晚霞¤ 2024-08-27 09:24:14

通过 using 语句,根据需要创建尽可能多的 SqlConnection,寿命尽可能短:

using (var connection = new SqlConnection(...)) {
  connection.Open();
  ...
}

Sql 连接是从连接池中获取的,它将自动为您管理争用。

请参阅:http://msdn.microsoft.com/en-我们/library/8xx3tyca(VS.80).aspx

Create as many SqlConnections as you need, as shortly lived as possible, through the using statement:

using (var connection = new SqlConnection(...)) {
  connection.Open();
  ...
}

Sql connections are taken from a connection pool, which will automatically manage contention for you.

See: http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80).aspx

网白 2024-08-27 09:24:14

创建一个新连接(并正确处置)并利用连接池

Create a new one (and dispose properly) and utilize connection pooling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文