ExecuteNonQuery需要一个开放且可用的连接。连接的当前状态已关闭。

时间:2015-02-17 05:53:24

标签: c# asp.net c#-4.0 ado.net c#-5.0

这看起来很傻但我不能指责这个。我在这做错了什么?这是一个常见的错误,但我似乎没有像在这里的其他几十个帖子上犯同样的错误...

    public static string Insert(SqlCommand cmd, SqlConnection connection) 
    {
        //feedback to user on whether the insert was successful
        string success = "Success! Thank you for contributing to this project";

        int added = 0;

        //connect and insert the data
        try
        {
            using (connection)
            {
                connection.Open();
                added = cmd.ExecuteNonQuery();

                //update success variable
                success += "\n" + added.ToString() + " records inserted.";
            }//end using(connection)
        }//end try

        catch (Exception err)
        {
            //if we have an error, return this message for debugging purposes for now
            string message = err.Message;
            return message;
        }//end catch

        return success;
    }//end Insert()

1 个答案:

答案 0 :(得分:3)

您的Command对象可能没有连接,因为您将ConnectionCommand传递给您的方法。您需要将连接分配给命令对象属性Connection

try
{
    using (connection)
    {
        cmd.Connection = connection; //Here assign connection to command object
        connection.Open();
        added = cmd.ExecuteNonQuery();

        //update success variable
        success += "\n" + added.ToString() + " records inserted.";
    }//end using(connection)
}//end try