【问题标题】:Add date to sqlserver in yyyy-mm-dd在 yyyy-mm-dd 中将日期添加到 sqlserver
【发布时间】:2015-07-08 09:18:32
【问题描述】:

当我使用以下方法将 lastImportedDate(dd-mm-yyyy) 添加到 sql 服务器时,一切都很好。在数据库中,日期是 yyyy-mm-dd

但是在切换日期和月份的同一台服务器上添加 lastImportedDate(dd-mm-yyyy) 与不同的电脑。在数据库中,日期是 yyyy-dd-mm。

internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, string periodStart, string periodEnd)
{
     // Create SQL connection #connection
     SqlConnection sqlConnection1 = new SqlConnection(Connection.connectionString());
     SqlCommand cmd = new SqlCommand();
     cmd.CommandType = CommandType.Text;

     string periodstartQuery = periodStart;
     string periodEndQuery = periodEnd;

     // Create query with values and execute query
     if (!periodStart.Equals("NULL"))
     {
         periodstartQuery = " '" + periodStart + "'";
     }

     if (!periodEnd.Equals("NULL"))
     {
         periodEndQuery = " '" + periodEnd + "'";
     }

     cmd.CommandText = "Insert into CarsSellout (CustomerID, type, lastImportedDate, PeriodStart, PeriodEnd) VALUES ('" + CustomerID + "', '" + type + "', '" + lastImported + "', " + periodstartQuery + ", " + periodEndQuery + ")";
     cmd.Connection = sqlConnection1;
     sqlConnection1.Open();
     cmd.ExecuteNonQuery();
     sqlConnection1.Close();
}

请注意,电脑上的日期设置都设置为 dd-mm-yyyy。

如果您需要更多信息,请添加评论!

在这种情况下会出现什么问题?

【问题讨论】:

  • in database the date is yyyy-dd-mm 是什么意思?
  • 你的方法periodStartperiodEnd的参数是字符串。更改为datetime。还将数据库中的列类型从 varchar 更改为 datetime
  • a) 您的数据应该作为日期字段而不是文本存储在数据库中; b) 使用参数化 SQL。它可以很好地解决这个问题,它还可以保护您免受 SQL 注入攻击。永远,永远,永远不要像这样构建 SQL。
  • 日期格式是文化敏感的。尝试使用特定的 CultureInfo,例如 en-US 或 Invariant。另一种选择是使用 ToString("yyyyMMdd") 等明确格式化您的日期。
  • @SvenL:完全没有理由使用字符串格式,IMO。

标签: c# sql-server date


【解决方案1】:

不要插入您的 DateTime 值及其字符串表示形式。将您的 DateTime 值直接添加到您的参数化查询中。

SQL Server 以二进制格式保存您的 DateTime 值。他们没有任何格式之类的。您所看到的yyyy-MM-dddd-MM-yyyy 只是它们的文本 表示。

为不同的服务器生成DateTime 实例的不同字符串表示通常,因为它们使用不同的文化设置。但由于您没有显示任何生成字符串的相关代码,我们永远不知道。

说到,你应该总是使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。

请仔细阅读;

作为最佳实践,使用using statement 自动处理您的连接和命令,而不是手动调用Close 方法。

using(var con = new SqlConnection(conString))
using(var cmd = con.CrateCommand())
{
    // Define your CommandText with parameterized query.
    // Define your parameters and their values. Add them with Add method to your command
    // Open your connection
    // Execute your query
}

【讨论】:

  • 谢谢你的明确回答,我会记住的!
  • @JP..t 很高兴听到这个消息。
猜你喜欢
  • 2013-01-28
  • 2016-01-02
  • 1970-01-01
  • 2021-10-16
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多