KingDollar
KingDollar

Reputation: 47

Resolving the error: There is already an open DataReader associated with this Command which must be closed first

I got this error :

"There is already an open DataReader associated with this Command which must be closed first"

private readonly object _syncRoot = new object();

public void SqlConnect(string server, string db, string user, string pw)
{
    lock (_syncRoot)
    {
       new_conn = new SqlConnection("Server=" + server + ";Database=" + db + ";User Id=" + user + ";Password=" + pw + ";");
       new_conn.Open();
    }
}

public string ReadString(string query)
{
    string strResult = null;
    using (SqlCommand command = new SqlCommand(query, new_conn))
    {
         using (SqlDataReader reader = command.ExecuteReader())
         {

             while (reader.Read())
             {
                    strResult = Convert.ToString(reader[0]);
             }
             reader.Close();
         }
    }
    return strResult;
}

I can't find what is wrong with that code?

Upvotes: 1

Views: 750

Answers (1)

Mickael Thumerel
Mickael Thumerel

Reputation: 536

Before calling SqlCommand you must check if your connection is still alive using the new_com.Status properties.

Personally i use a property to get the connection and in the get of this property i create the connection if it doesn't exist and if the status is not open i open it.

Upvotes: 1

Related Questions