加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在执行多个查询时保持Connection处于打开状态?

发布时间:2020-12-15 18:13:29 所属栏目:百科 来源:网络整理
导读:我正在使用多个查询从我的应用程序中的同一服务器中提取数据.问题是我每次有新查询时都必须打开一个新连接. 是否有可能: 打开连接 运行查询 拉结果 运行另一个查询 拉另一个结果 运行最终查询 拉另一个结果 关闭连接. 解决方法 虽然你可能还不知道,但你正确
我正在使用多个查询从我的应用程序中的同一服务器中提取数据.问题是我每次有新查询时都必须打开一个新连接.

是否有可能:

>打开连接
>运行查询
>拉结果
>运行另一个查询
>拉另一个结果
>运行最终查询
>拉另一个结果
>关闭连接.

解决方法

虽然你可能还不知道,但你正确地做到了.

打开连接,执行查询,关闭它.优选使用使用块或尝试/最终.

这可能听起来像很多开销,但SQL Server的.NET Framework数据提供程序中的连接池实际上会为您优化这一点.

实际上建议关闭连接.
以下是文档中的引用:

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.

以下是一些执行此操作的代码示例:

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

以供参考:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读