2013-03-23 36 views
1

我得到一个错误:如何运行的SqlCommand而内(dr.read())

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

我的代码:

SqlCommand cmd = new SqlCommand("SELECT * FROM shoppingcart", con); 
SqlDataReader dr; 
con.Open(); 

dr = cmd.ExecuteReader(); 

while (dr.Read()) 
{ 
       found = true; 
       productdate = Convert.ToDateTime(dr.GetString(4)); 
       string ago1 = string.Format("{0:MM/dd/yy}", Convert.ToString(productdate)); 
       string productdate1 = string.Format("{0:MM/dd/yy}", Convert.ToString(ago)); 
       int productqty = Convert.ToInt32(dr.GetValue(3)); 
       int productID = Convert.ToInt32(dr.GetValue(2)); 
       int cartID = Convert.ToInt32(dr.GetValue(0)); 
       if (productdate < ago) 
       { 

        SqlCommand updateproducts = new SqlCommand("UPDATE products SET [email protected] WHERE [email protected]", con); 
        updateproducts.Parameters.AddWithValue("@ProductQuantity", productqty); 
        updateproducts.Parameters.AddWithValue("@ProductID", productID); 
        updateproducts.ExecuteNonQuery(); 

        SqlCommand deletecart = new SqlCommand("DELETE FROM shoppingcart WHERE [email protected]", con); 
        deletecart.Parameters.AddWithValue("@ID", cartID); 
        deletecart.ExecuteNonQuery(); 
       } 
} 
con.Close(); 

我需要执行更新和删除内while(dr.read())但是当我尝试关闭连接然后再次打开时,弹出错误,同时将停止并出现错误,表示ExecuteReader已接近。请帮帮我。

回答

5

如果您添加到您的连接字符串,它将使该代码的工作:

MultipleActiveResultSets=True; 

docs

Multiple Active Result Sets (MARS) is a feature that allows the execution of multiple batches on a single connection. In previous versions, only one batch could be executed at a time against a single connection. Executing multiple batches with MARS does not imply simultaneous execution of operations.

就像一般的笔记 - 这是更好的做法,包什么在使用块中实现IDisposable。这样资源将被正确关闭并释放。

所以你的连接可以裹得像个:

using (var con = new SqlConnection(connectionString)) 
{ 
... 
} 
SqlCommandSqlDataReader对象

同样。

+0

该死的非常感谢你,我一直在为此工作一个小时,这就是我需要的一切。非常感谢你:D – Reynan 2013-03-23 10:06:58

+0

没问题@ReynanCapco,一定要标记你的答案,回答为答案。 – 2013-03-23 10:21:30