【发布时间】: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.MinValuesql-server 不支持(从 1753 年 1 月 1 日开始)。
标签: c# sql-server datetime sqlcommand sqlparameter