ADO.NET:ExecuteScalar()连接问题

时间:2015-03-20 09:27:24

标签: ado.net

这是我的C#代码

protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
    {
        if (sqlcon.State == ConnectionState.Closed)
            sqlcon.Open();
        foreach (Model Rate in Items)
        {
            SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
            sccmd.CommandType = CommandType.StoredProcedure;
            sccmd.Parameters.Add("@ItemsId", SqlDbType.Int).Value = Rate.Id;
            sccmd.Parameters.Add("@RMId", SqlDbType.Int).Value = Rate.HeadId;
            sccmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = Rate.Date;
            sccmd.Parameters.Add("@Price", SqlDbType.Decimal).Value = Rate.Price;
            sccmd.Parameters.Add("@UserId", SqlDbType.Int).Value = UserId;
            if (Rate.Id == 0)
            {
                Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
            }
            else
                sccmd.ExecuteScalar();
        }
        sqlcon.Close();
        return true;
    }

反复点击添加按钮,这给了我这个错误

  

其他信息:ExecuteScalar需要开放且可用   连接。连接的当前状态已关闭。

导致此错误的原因是什么?如何解决?

1 个答案:

答案 0 :(得分:2)

尝试这样:

protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
{
    if (sqlcon.State == ConnectionState.Closed)
{
        sqlcon.Open();
    foreach (Model Rate in Items)
    {
        SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
        sccmd.CommandType = CommandType.StoredProcedure;
        sccmd.Parameters.Add("@ItemsId", SqlDbType.Int).Value = Rate.Id;
        sccmd.Parameters.Add("@RMId", SqlDbType.Int).Value = Rate.HeadId;
        sccmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = Rate.Date;
        sccmd.Parameters.Add("@Price", SqlDbType.Decimal).Value = Rate.Price;
        sccmd.Parameters.Add("@UserId", SqlDbType.Int).Value = UserId;
        if (Rate.Id == 0)
        {
            Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
        }
        else
            sccmd.ExecuteScalar();
    }
    sqlcon.Close();
    }
    return true;
}