【问题标题】:ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.ExecuteNonQuery 需要一个开放且可用的连接。连接的当前状态为关闭。
【发布时间】:2015-04-17 19:09:44
【问题描述】:

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

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

【问题讨论】:

  • 你从哪里得到错误?
  • 您是否收到任何错误消息?运行该函数后返回什么?
  • 对!我并不完全清楚。我在声明 code added = cmd.ExecuteNonQuery(); 之后立即收到标题中的错误code 正在运行。然后直接跳转到错误处理代码。

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


【解决方案1】:

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

【讨论】:

  • 这就是我的问题。 (顺便说一句,这是我在 StackOverFlow 上的处女帖,感谢您让我感到宾至如归:)
  • 不客气@JacquesPluviose,欢迎来到 SO,很高兴看到您的第一篇文章与您的努力和格式。
猜你喜欢
  • 2011-04-02
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
相关资源
最近更新 更多