【问题标题】:SqlCommand ExecuteNonquery strange exceptionSqlCommand ExecuteNonquery 奇怪的异常
【发布时间】:2013-11-07 08:11:51
【问题描述】:

我想在 SQL Server 数据库中插入一条记录,但在执行 ExecuteNonQuery() 过程时遇到了一个奇怪的异常。我得到了这个例外:

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

但是我的问题与此无关。我确信我的连接的当前状态是打开的。我的问题是查询中的参数之一。这是我的查询:

                  sql = "update EMAIL_CONNECTIONS " +
                             "set END_DATE=@EndDate, " +
                             "STATUS=@Status, " +
                             "STATUS_DATE=@StatusDate, " +
                             "CATEGORY_CODE=@CategoryCode, " +
                             "EMAILOUT_SENTDATE=@EmailOutSentDate, " +
                             "TO_ADDRESS=@ToAddress " +
                             "where SESSIONID=@SessionId " +
                             "and STATUS = 'Inprocess'; ";
                sql += "insert into ICS_EMAIL_CONNECTIONS_TRX(SESSIONID, AGENTID, STATUS, FIELD1) " +
                       "values(@SessionId, @AgentId, @Status, 'Sended this mail')";

由于@EmailOutSentDate 参数而引发异常。它不接受日期时间格式或我不知道的东西。当我将 DateTime.Now 赋予此参数时,查询将成功运行。我还尝试了 DBNull.Value 并且查询运行完美。 DateTime 问题与异常无关。

   SqlConnection _cnn = new SqlConnection();
   _cnn.ConnectionString = connectionString;
   _cnn.Open();
    SqlCommand cmd = new SqlCommand(sql, _cnn);                    
   cmd.Parameters.Add(new SqlParameter("@EndDate", DateTime.Now));
   cmd.Parameters.Add(new SqlParameter("@Status", "Sent"));
   DateTime result = DateTime.MinValue;
   result = DateTime.ParseExact(result.ToString("yyyy-mm-dd HH:mm:ss.fff"), "yyyy-mm-dd HH:mm:ss.fff", null);
                DateTime newdate = DateTime.SpecifyKind(result, DateTimeKind.Local);
   cmd.Parameters.Add(new SqlParameter("@EmailOutSentDate", newdate));                   
   cmd.Parameters.Add(new SqlParameter("@ToAddress", interaction.AllAttributes["To"]));
   cmd.Parameters.Add(new SqlParameter("@StatusDate", DateTime.Now));
   cmd.Parameters.Add(new SqlParameter("@CategoryCode", long.Parse(CategoryCode)));
   cmd.Parameters.Add(new SqlParameter("@SessionId", interaction.Id));
   cmd.Parameters.Add(new SqlParameter("@AgentId", Agent.AgentId));
   cmd.CommandType = System.Data.CommandType.Text;
   cmd.ExecuteNonQuery();
   cmd.Dispose();

如您所见,我也尝试过 DateTime.Kind 属性,但仍然抛出相同的异常。哪里有问题?有什么建议吗?

【问题讨论】:

  • 异常的堆栈跟踪是否指向此处显示的 ExecuteNonQuery?还是此异常可能来自您未显示的某些异常处理?另外:using。你应该是using(var _cnn = ...)using(var cmd = ...)
  • "它不接受日期时间格式什么的" - 日期时间不作为文本发送到 sql server;这不是格式问题
  • 顺便说一句;不相关 - 重新构建 sql 值的方式 - 你知道你可以更简单地使用逐字字符串文字来做到这一点吗?即sql = @"{your text here; can include line feeds etc just by pressing return}";
  • 您应该对连接和命令使用using 语句。否则连接会在出错时保持打开状态。
  • 你在这里做什么?您将DateTime.MinValue 转换为string,然后使用DateTime.ParseExact 转换回DateTime,最后您使用DateTime.SpecifyKind。结果是一样的:DateTime.MinValue sql-server 不支持(从 1753 年 1 月 1 日开始)。

标签: c# sql-server datetime sqlcommand sqlparameter


【解决方案1】:

你到底想做什么?看起来您正在尝试插入一个虚拟日期而不是在数据库中具有空值?如果是这种情况,您应该坚持插入空值而不是没有实际意义的日期。

如果您确实有一个不想作为本地化值插入的 DateTime 值,这可能会对您有所帮助:How to produce localized date string with CultureInfo

这是我们在不使用 EF 时在旧 db 层中使用的更新方法,它将为您提供更安全的代码。请注意,在您真正需要执行查询之前,您不需要打开连接,并且使用 using 语句将确保您处理掉 SqlCommand。 _connection 属性是私有的,用于该类中的所有方法,由 DependencyInjection 在构造函数中设置。

_connection = new SqlConnection(this._connectionString);

public int Update(string query, Dictionary<string, string> commandParams)
    {
        int affectedRows = 0;
        using (SqlCommand command = new SqlCommand(query, _connection))
        {
            command.CommandType = CommandType.Text;
            foreach (var param in commandParams)
            {
                if (param.Value == null)
                    command.Parameters.AddWithValue(param.Key, DBNull.Value);
                else
                    command.Parameters.AddWithValue(param.Key, param.Value);
            }

            try
            {
                _connection.Open();
                affectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _connection.Close();
                command.Parameters.Clear();
            }
        }

        return affectedRows;
    }

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多