简体   繁体   中英

Close or Release my DataReader or SqlConnection

I have the following code to retrieve column names from a 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);
            }

I've tried using conn.Close() to close the connection but 'Invalid attempt to call Read when reader is closed.' gets returned.

Or the connection times out with 'Internal connection fatal error. Error state: 15, Token : 0' 00:00:31.1460115

How do I properly close this connection and move out of the using block?

General structure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM