关闭或释放我的 DataReader 或 SqlConnection

Close or Release my DataReader or SqlConnection

我有以下代码从 table

中检索列名
conn.Open()
using(SqlCommand cmd = new SqlCommand(colQuery, conn))
    {
        try
        {
            using(SqlDataReader dr = cmd.ExecuteReader())
            {
                dr.Read();

                    var columns = new List<string>();

                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        string colName = dr.GetName(i);
                        columns.Add(dr.GetName(i));
                        repColsString += colName;
                    }                   
                }
                break;
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(ex.Message);
            }

我试过使用 conn.Close() 关闭连接,但返回 'Invalid attempt to call Read when reader is closed.'。

或者连接超时 'Internal connection fatal error. Error state: 15, Token : 0' 00:00:31.1460115

如何正确关闭此连接并移出 using 块?

一般结构:

using conn = new SqlConnection(...) {
    conn.Open();
    using cmd = new SqlCommand(conn) {
        dr = cmd.ExecuteReader();
        while (dr.read) {
            // do stuff
        }
    }
}