SqlDataReader.Close 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
关闭 SqlDataReader 对象。
public:
virtual void Close();
public:
override void Close();
public void Close();
public override void Close();
abstract member Close : unit -> unit
override this.Close : unit -> unit
override this.Close : unit -> unit
Public Sub Close ()
Public Overrides Sub Close ()
实现
示例
以下示例创建一个 SqlConnection、一个 SqlCommand和一个 SqlDataReader。 该示例读取数据,并将其写出到控制台窗口。 然后,代码关闭 .SqlDataReader 代码 SqlConnection 块末尾 using 自动关闭。
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command =
new SqlCommand(queryString, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
}
}
Private Sub ReadOrderData(ByVal connectionString As String)
Dim queryString As String = _
"SELECT OrderID, CustomerID FROM dbo.Orders;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
' Call Read before accessing data.
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
End While
' Call Close when done reading.
reader.Close()
End Using
End Sub
注解
使用Close关联SqlDataReader以用于任何其他目的时,必须显式调用SqlConnection该方法。
该方法 Close 填充输出参数的值,返回值,并 RecordsAffected增加关闭 SqlDataReader 用于处理大型查询或复杂查询所需的时间。 当返回值和受查询影响的记录数不重要时,通过在调用SqlDataReader方法之前调用Cancel关联的SqlCommand对象的方法来缩短关闭Close结束记录所需的时间。
Caution
请勿在类的方法中Close调用或Dispose调用 Finalize Connection、DataReader 或任何其他托管对象。 在终结器中,应仅释放类直接拥有的非托管资源。 如果类不拥有任何非托管资源,则不要在类定义中包含 Finalize 方法。 有关详细信息,请参阅垃圾回收。