Visual C++ 6 writing a date/time value into a database

Evgeny Shupik 191 Reputation points
2022-05-22T12:23:53.357+00:00

Hello everybody! :-) Need some advice about writing data in the database using MFC (Visual C++ 6). There is a table HISTORY containing fields: employer_code, device_code and Date. So first two fileds are 'long int' type and Date is a 'date/time' type. Trying to write a new record:

sSql.Format("INSERT INTO History (device_code,employer_code) VALUES ('%d','%d');", max_device_code,employer_code);
database.ExecuteSQL(sSql);

It's OK but I don't know how to write Date filed - what kind of VALUES should I provide? I mean:

sSql.Format("INSERT INTO History (device_code,employer_code, Date) VALUES ('%d','%d','%???');", max_device_code,employer_code,date);
database.ExecuteSQL(sSql);

Thank you for help.

Developer technologies | C++
{count} votes

2 answers

Sort by: Most helpful
  1. Guido Franzke 2,191 Reputation points
    2022-05-23T05:59:48.607+00:00

    Hello,
    normally speaking, a database uses a date/time format in English notation, means: "yyyy-mm-dd hh:mm:ss".
    You don't say what exact datatype you use for your date variable.
    Read the documentation of your date datatype how to get the single values for year, month, day, hour, minute and second.
    Then the source code would look like this (just replace the GetYear,GetMonth,... functions with the corresponding functions for your date variable):

    sSql.Format("INSERT INTO History (device_code,employer_code, Date) VALUES ('%d','%d','%4i-%02i-%02i %02i:%02i:%02i'", max_device_code, employer, date.GetYear(), date.GetMonth(), date.GetDay(), date.GetHours(), date.GetMinutes(), date.GetSeconds());
    

    Regards, Guido


  2. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2022-06-02T02:45:21.127+00:00

    Hi, @Evgeny Shupik

    This is the test snippet for your reference:

    db.ExecuteSQL(  
    		_T("INSERT INTO Table1  ")  
    		_T("VALUES  (5,'5/30/2022 4:02:05 AM') ")//ID Date  
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.