简体   繁体   中英

C# and SQL server datetime format

I have the following C# method to update a value in a SQL server:

public void Save()
{
    int TotalFail = TotalRecords - SuccessCount;

    DataAccess_MSSQLServer oDAM = new DataAccess_MSSQLServer();

    try
    {                                                                                                                                                                                                                                           
        oDAM.Update("Update TBL_FulfilmentBatch SET ReturnDate = " + oDAM.GetFieldValueSQL(processDate) + ", TotalSuccess = " + oDAM.GetFieldValueSQL(SuccessCount) + ", TotalFail = " + oDAM.GetFieldValueSQL(TotalFail) + ", ProcessedDate = " + oDAM.GetFieldValueSQL(DateTime.Now.ToString("yyyyMMddHHmmss")) + " WHERE FulfilmentHouseID = (SELECT FulfilmentHouseID FROM TBL_fulfilmentHouse WHERE [Description] Like 'Current') AND BatchNumber = " + oDAM.GetFieldValueSQL(batchNumber));
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
    }

}

Where

oDAM.GetFieldValueSQL

is a method used to format strings etc for SQL statements.

The string processDate has the value: 2015-07-23

The field this corresponds to in the database is a datetime field.

I also have:

ProcessedDate = " + oDAM.GetFieldValueSQL(DateTime.Now.ToString("yyyyMMddHHmmss"))

which inserts a C# datetime field in the database.

These 2 datetime fields should now be in the same date format.

The problem is that when inserted into the databse, they come out as follows:

在此处输入图片说明

Which is opposite formats.

why is this happening?

They are both being passed in as strings, in the same format.

There is nothing in the table that tells it to convert to a particular datetime format.

Older entries of the ProcessedDate column are in American format.

Does it think this date is in American format aswell?

What can I do?

You should use parameterized queries.

If you keep trying, eventually you'll manage to tweak your string into format that "works". For your current database instance, running the client application on your computer. It might break on the 13th of the month (when days are mistaken for months).

The ADO.NET providers can translate a DateTime and other primitive types for you, and prevent SQL injection vulnerabilities at the same time. You will probably even see a performance gain if you reuse the DbCommand s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM