JP.*_*..t 0 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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,电脑上的日期设置都设置为dd-mm-yyyy.
如果您需要更多信息,请添加评论.
在这种情况下会出现什么问题?
千万不能将您DateTime与他们的字符串表示的值.将您的DateTime值直接添加到参数化查询中.
SQL Server DateTime以二进制格式保存您的值.他们没有任何格式或东西.你看到它们yyyy-MM-dd或dd-MM-yyyy只是它们的文字表示.
DateTime为不同的服务器生成实例的不同字符串表示形式,通常是因为它们使用不同的区域性设置.但由于您没有显示任何生成字符串的相关代码,我们永远不会知道.
说到,您应该始终使用参数化查询.这种字符串连接对SQL注入攻击是开放的.
请仔细阅读;
作为最佳实践,使用usingstatement自动处理连接和命令,而不是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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |