c# - 执行多个查询时如何保持连接打开?

标签 c# .net asp.net

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

是否有可能:

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

最佳答案

虽然您可能还不知道,但您做对了。

打开连接,进行查询,然后关闭它。最好使用 using block 或 try/finally

这听起来可能开销很大,但 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

关于c# - 执行多个查询时如何保持连接打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/682855/

相关文章:

c# - 在 LINQ 中左加入 OrderBy

asp.net - 将 default.aspx 重定向到根虚拟目录

jquery - 使用 jquery 更改页面加载时的列值

c# - 当 checkbox.checked 值设置为 true 时强制回发

c# - 让 VS 测试资源管理器只显示测试名称而不是完整的类型名称

c# - WPF 应用程序在第一次交互后停止/卡住,例如单击按钮

c# - 使用 LINQ 将一个对象属性列表更新为其他列表

c# - 在 log4net 中格式化自定义属性

.Net 程序被编译为名为 "assemblies."的 DLL 或 EXE 文件类型 程序集是否包含机器可执行代码

c# - 如何在路径段中包含数字(散列)字符#?