SqlDataReader.Close 方法
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
关闭 SqlDataReader 对象。
public:
virtual void Close();
public:
override void Close();
C#
public void Close();
C#
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
自动关闭 。
C#
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
用于处理大型或复杂查询的时间。 当返回值和受查询影响的记录数不重要时,可以通过在调用 方法之前调用Cancel关联SqlCommand对象的 方法来缩短关闭 SqlDataReader
所需的时间Close
。
注意
不要在 类的 方法中Finalize
调用 Close
或 Dispose
对 Connection、DataReader 或任何其他托管对象调用 或 。 在终结器中,应仅释放类直接拥有的非托管资源。 如果类不拥有任何非托管资源,则不要在类定义中包含 Finalize
方法。 有关详细信息,请参阅垃圾回收。
产品 | 版本 |
---|---|
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |