Cod*_*ain 116
尽量避免使用这样的读者:
SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
reader.Close(); // <- too easy to forget
reader.Dispose(); // <- too easy to forget
connection.Close(); // <- too easy to forget
Run Code Online (Sandbox Code Playgroud)
而是将它们包装在using语句中:
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
} // reader closed and disposed up here
} // command disposed here
} //connection closed and disposed here
Run Code Online (Sandbox Code Playgroud)
using语句将确保正确处理对象和释放资源.
如果你忘了那么你就要把清洁工作留给垃圾收集器,这可能需要一段时间.
Joe*_*Joe 50
请注意,使用SqlCommand.ExecuteReader()实例化处置SqlDataReader 不会关闭/处置基础连接.
有两种常见的模式.在第一个中,读者在连接范围内打开和关闭:
using(SqlConnection connection = ...)
{
connection.Open();
...
using(SqlCommand command = ...)
{
using(SqlDataReader reader = command.ExecuteReader())
{
... do your stuff ...
} // reader is closed/disposed here
} // command is closed/disposed here
} // connection is closed/disposed here
Run Code Online (Sandbox Code Playgroud)
有时,使用数据访问方法打开连接并返回阅读器很方便.在这种情况下,使用CommandBehavior.CloseConnection打开返回的阅读器非常重要,这样关闭/部署阅读器将关闭底层连接.模式看起来像这样:
public SqlDataReader ExecuteReader(string commandText)
{
SqlConnection connection = new SqlConnection(...);
try
{
connection.Open();
using(SqlCommand command = new SqlCommand(commandText, connection))
{
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch
{
// Close connection before rethrowing
connection.Close();
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
并且调用代码只需要处理读者:
using(SqlDataReader reader = ExecuteReader(...))
{
... do your stuff ...
} // reader and connection are closed here.
Run Code Online (Sandbox Code Playgroud)
Kon*_*Kon 10
为安全起见,请将每个SqlDataReader对象包装在using语句中.
归档时间: |
|
查看次数: |
66394 次 |
最近记录: |