mysqlcastingc++-clidatetime-formatstr-to-date

Insert / Convert date from: C++ To mySQL db


I'm a beginner in c++, this is part of my Task for an interview. Everything else works fine, except that I don't know how to convert String to Date, when it comes to pass the record to the database. Or just pass date (or DateTime) to the database. I found a lot of things in google, but couldn't figure it out how to do this in the most simple way. Also later I'll add HH:mm, because I'll have to calculate with hours/mins too. Here's the part of the code:

DateTime startTime = dateTimePicker1->Value;
String^ startTimeString = startTime.Year.ToString() +"-"+ startTime.Month.ToString() +"-"+ startTime.Day.ToString();

MySqlCommand^ cmd = gcnew MySqlCommand("insert into activity_db values('" + name + "','" + category + "','SELECT STR_TO_DATE(" + startTimeString + ",%Y-%m-%d)')", con);


Solution

  • use

    MySqlCommand^ cmd = gcnew MySqlCommand("insert into activity_db values('" + name + "','" + category + "',STR_TO_DATE('" + startTimeString + "','%Y-%m-%d'))", con);
    

    So you will get the correct mysql command

    insert into activity_db values('name','category',STR_TO_DATE('2020-01-01','%Y-%m-%d'))
    

    And you should urgenty takem alook at prepared statements