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

ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

这看起来很愚蠢,但我不能确定这一点。我在这里做错了什么?这是一个常见的错误,但我似乎没有犯与这里其他几十个帖子相同的错误...

    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()

您的 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