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
}
}
}