我怎么能执行多个查询时保持连接打开? [英] How can I keep a Connection open when performing multiple queries?

查看:116
本文介绍了我怎么能执行多个查询时保持连接打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的多个查询,从我的应用程序在同一服务器中提取数据。问题是,我必须每次我有一个新的查询打开一个新的连接。

I am using multiple queries to pull data from the same server in my application. The issue is that I have to open a new connection every time I have a new query.

它甚至有可能为:

  • 打开连接
  • 运行查询
  • 牵引结果
  • 运行另一个查询
  • 在拉另一结果
  • 运行最终查询
  • 在拉另一结果
  • 关闭连接。

推荐答案

虽然你可能还不知道,你正在做正确的。

Although you may not yet know it, you are doing it correctly.

打开连接,执行查询,关闭它。 preferably使用使用块或尝试 / 最后

Open the connection, do your query, close it. Preferably using a using block or try/finally.

这听起来像一个很大的开销,但在.NET Framework数据提供程序的SQL Server连接池实际上将优化这个给你。

This may sound like a lot of overhead, but the connection pool in the .NET Framework Data Provider for SQL Server will actually optimize this for you.

在事实上关闭连接建议。 下面是从文档报价:

In fact closing the connection is recommended. Here is a quote from the documentation:

建议您始终   关闭当你连接   使用它,才能完的   连的情况下返回到池中。   这是可以做到用任   的关闭或Dispose方法   Connection对象。连接这   未明确关闭可能不   添加或返回到池中。对于   例如,已经连接   超出范围但尚未   明确封闭只会   返回到连接池,如果   最大池容量已经达到,   该连接仍然有效。

It is recommended that you always close the Connection when you are finished using it in order for the connection to be returned to the pool. This can be done using either the Close or Dispose methods of the Connection object. Connections that are not explicitly closed might not be added or returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be returned to the connection pool if the maximum pool size has been reached and the connection is still valid.

下面是一些code,做一个这样的例子:

Here is an example of some code that does this:

try {
    conn.Open();
    // Perform query here
} finally {
    conn.Close();
}

有关参考:

<一个href="http://msdn.microsoft.com/en-us/library/8xx3tyca%28VS.71%29.aspx">http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.71).aspx

这篇关于我怎么能执行多个查询时保持连接打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆