C# 在yyyy mm dd中将日期添加到sqlserver
当我使用以下方法将lastImportedDate(dd-mm-yyyy)添加到sql server时,一切正常。在数据库中,日期为yyyy-mm-dd 但在切换日期和月份时,在同一服务器上的不同pc上添加lastImportedDate(dd-mm-yyyy)。在数据库中,日期为yyyy dd mmC# 在yyyy mm dd中将日期添加到sqlserver,c#,sql-server,date,C#,Sql Server,Date,当我使用以下方法将lastImportedDate(dd-mm-yyyy)添加到sql server时,一切正常。在数据库中,日期为yyyy-mm-dd 但在切换日期和月份时,在同一服务器上的不同pc上添加lastImportedDate(dd-mm-yyyy)。在数据库中,日期为yyyy dd mm internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, str
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
如果您需要更多信息,请添加评论
这种情况下会出现什么问题?请不要插入带有字符串表示形式的
DateTime
值。将DateTime
值直接添加到参数化查询中
SQL Server以二进制格式保存DateTime
值。他们没有任何格式什么的。您所看到的yyyy-MM-dd
或dd-MM-yyyy
只是它们的文本表示
为不同的服务器生成DateTime
实例的不同字符串表示形式通常是因为它们使用不同的区域性设置。但由于您没有显示任何生成字符串的相关代码,我们永远也不知道
说到这里,你应该经常使用。这种类型的字符串连接对攻击是开放的
请仔细阅读
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
}
数据库中日期为yyyy dd mm的
是什么意思?方法的参数periodStart
和periodsend
是字符串。更改为datetime
。还可以将数据库中的列类型从varchar
更改为datetime
。a)您的数据应作为日期字段而不是文本存储在数据库中;b) 请使用参数化SQL。它可以很好地解决这个问题,并且还可以保护您免受SQL注入攻击。永远,永远,永远不要像这样构建SQL。日期格式是区分区域性的。尝试使用特定的CultureInfo,如en US或Invariant。另一种选择是使用ToString(“yyyyMMdd”)或类似的格式显式设置日期格式。@SvenL:我认为,根本没有理由使用字符串格式。谢谢你给出的明确答案,我会记住的@听到这个消息我不高兴。