SqlDataReader.Close 方法

定义

关闭 SqlDataReader 对象。

public:
 override void Close();
public:
 virtual void Close();
public override void Close ();
public void Close ();
override this.Close : unit -> unit
abstract member Close : unit -> unit
override this.Close : unit -> unit
Public Overrides Sub Close ()
Public Sub Close ()

实现

示例

以下示例创建 SqlConnectionSqlCommand、 和 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 用于处理大型或复杂查询的时间。 当返回值和受查询影响的记录数不重要时,可以通过在调用 方法之前调用Cancel关联SqlCommand对象的 方法来缩短关闭 SqlDataReader 所需的时间Close

注意

不要在 类的 方法中Finalize调用 CloseDispose 对 Connection、DataReader 或任何其他托管对象调用 或 。 在终结器中,应仅释放类直接拥有的非托管资源。 如果类不拥有任何非托管资源,则不要在类定义中包含 Finalize 方法。 有关详细信息,请参阅垃圾回收

适用于

另请参阅