将日期时间发送到 SQL 表时出现问题

本文关键字:问题 SQL 日期 时间 | 更新日期: 2023-09-27 18:34:57

我正在用C#编写WinForms代码,基本上有以下内容:

DateTime localDate = DateTime.UtcNow;
SqlConnection Conn = new SqlConnection("....[connection info]....");
Conn.Open();
SqlCommand sqlcomm = new SqlCommand("INSERT INTO dbo.Call VALUES(...., @Time,...);", Conn);
sqlcomm.Parameters.Add("@Time", SqlDbType.DateTime);
sqlcomm.Parameters["@Time"].Value = localDate;
Int32 o = sqlcomm.ExecuteNonQuery();

这抛出了一个错误" When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object. "从我收集的信息来看,它认为localDate变量是一个字符串,但如果我写信给控制台localDate.GetType()它说System.DateTime.

数据库中"@Time"列设置为日期时间,因此这不是问题所在。有什么想法吗?

将日期时间发送到 SQL 表时出现问题

你快到了。 对于 Sql 服务器,请在这些行中思考

select cast(getdate() as time)

问题是在.net中没有时间这样的类型,所以你需要适应

SqlCommand sqlcomm = new SqlCommand(
    "INSERT INTO dbo.Call VALUES(...., cast(@Time as time),...);", Conn);
sqlcomm.Parameters.AddWithValue("@Time", localDate);

这就是你应该需要的。虽然,我认为,你甚至可能不需要添加 cast,因为 DB 引擎本身会尝试转换它。我认为,问题在于您明确表示您的类型SqlDbType.DateTime.但是如果你使用AddWithValue,提供者会为你做事。

既然@Frédéric提到TimeSpan,你也可以试试这个

sqlcomm.Parameters.AddWithValue("@Time", localDate.TimeOfDay);
' and no cast(@Time as time)

UTC 格式不是您在参数中指定的 sql 日期时间格式。

过去,我将 UTC 时间格式化为 yyyy-MM-dd 的时间。

给定此表架构:

create table dbo.call_history
(
  id          int      not null identity(1,1) primary key clustered ,
  my_date     date         null ,
  my_time     time         null ,
  my_datetime datetime     null ,
)

这段代码工作得很好:

using ( SqlConnection conn = new SqlConnection( connectString ) )
using ( SqlCommand cmd = conn.CreateCommand() )
{
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = @"
    insert dbo.call_history ( my_date , my_time , my_datetime )
    values                  ( @pDate  , @pDate  , @pDate      )
    select scope_identity()
  ";
  cmd.Parameters.AddWithValue( "@pDate" , DateTime.UtcNow );
  conn.Open();
  // double downcast required herebecause scope_identity()
  // returns numeric(38,0) which gets mapped to decimal
  int id = (int)(decimal) cmd.ExecuteScalar() ;
  conn.Close();
}