我收到一个错误:
已经有一个与此命令关联的打开的 DataReader,必须先关闭它。
我的代码:
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 ProductQuantity=ProductQuantity+@ProductQuantity WHERE ProductID=@ProductID", con);
updateproducts.Parameters.AddWithValue("@ProductQuantity", productqty);
updateproducts.Parameters.AddWithValue("@ProductID", productID);
updateproducts.ExecuteNonQuery();
SqlCommand deletecart = new SqlCommand("DELETE FROM shoppingcart WHERE ID=@ID", con);
deletecart.Parameters.AddWithValue("@ID", cartID);
deletecart.ExecuteNonQuery();
}
}
con.Close();
我需要在内部执行更新和删除,while(dr.read())
但是当我尝试关闭连接然后再次打开时会弹出错误,此时将停止并且会出现错误,表示ExecuteReader
已关闭。请帮我。