【问题标题】:how to set sql server filed date to mm/dd/yyyy如何将 sql server 归档日期设置为 mm/dd/yyyy
【发布时间】:2009-08-19 09:07:55
【问题描述】:

我无法插入使用 c# 语言 DateTime.Now.ToString()

在数据类型日期时间字段中插入 sqlserver

【问题讨论】:

  • 您可以将日期作为 YYYY-MM-DD 插入到 SQL Server 中,无论您的本地化如何,它每次都会起作用。

标签: c# datetime


【解决方案1】:

不要将您的 DateTime 值转换为字符串。改用参数化 SQL:

string sql = "INSERT INTO Your_Table (Your_Column) VALUES (@YourParam)";

using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
    cmd.Parameters.Add("@YourParam", SqlDbType.DateTime).Value = yourDate;

    conn.Open();
    cmd.ExecuteNonQuery();
}

【讨论】:

    【解决方案2】:

    您不必执行 ToString() 来插入 SQL 服务器数据库

    【讨论】:

      【解决方案3】:

      您的问题没有多大意义,但我认为您正在寻找这个:

      DateTime.Now.ToString(string format)
      

      这将以您想要的方式格式化 DateTime。

      不过,您确实不应该首先将 SQL 查询构建为字符串。您应该使用参数,它允许您提供 C# 非字符串对象而不是转换后的字符串。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2018-03-31
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多