我在我的应用程序中使用多个查询从同一服务器提取数据。问题是每次有新查询时我都必须打开一个新连接。
是否有可能:
- 打开连接
- 运行查询
- 拉取结果
- 运行另一个查询
- 拉取另一个结果
- 运行最终查询
- 拉取另一个结果
- 关闭连接。
最佳答案
虽然您可能还不知道,但您做对了。
打开连接,进行查询,然后关闭它。最好使用 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/