在yyyy-mm-dd中向sqlserver添加日期

时间:2015-07-08 09:18:32

标签: c# sql-server date

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

但是在同一台服务器上添加lastImportedDate(dd-mm-yyyy)和不同的pc,切换日期和月份。在数据库中,日期是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。

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

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

1 个答案:

答案 0 :(得分:7)

使用字符串表示形式插入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
}