我想向 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 属性,但仍然抛出相同的异常。问题出在哪里?有什么建议吗?