任何人都可以告诉我CommandBehavior.CloseConnection传递这个作为参数的用途和好处是com.ExecuteReader(CommandBehavior.CloseConnection)什么?
Jef*_*nal 19
在读取数据读取器时需要打开连接,并且希望尽快关闭连接.通过指定CommandBehavior.CloseConnection何时调用ExecuteReader,可确保代码在关闭数据读取器时关闭连接.
但是你应该已经立即处理你的连接(而不仅仅是关闭它们),在这种情况下,这样做最多只能获得边际(几乎肯定无法测量)的好处.
例如,此代码立即关闭其连接(并执行处理它所需的任何其他工作),而不指定命令行为:
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
// Do something with the rows
}
}
Run Code Online (Sandbox Code Playgroud)
用于CommandBehavior.CloseConnection创建连接但返回a的函数IDataReader.要非常小心Dispose()的IDbConnection例外只有在创建读者面前:
IDataReader ReadAll()
{
var connection = new SqlConnection(connectionString);
try
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM mytable";
var result = command.ExecuteReader(CommandBehavior.CloseConnection);
connection = null; // Don't dispose the connection.
return result;
}
finally
{
if (connection != null)
connection.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20656 次 |
| 最近记录: |