C++ store a modified MySQL timestamp as string

孤街醉人 提交于 2019-12-11 04:18:45

问题


I am currently trying to get a DATETIME key value from a MySQL database and save it as a string.

However I dont want the time to be in the usual MySQL format YYYY-MM-DD HH:MM:SS but rather in a 12 hour format like this: HH:MM:SS AM/PM

I already figured out how to "convert" the time format in the MySQL database to my desired format by using this:

sql::ResultSet* time = database->Query("SELECT DATE_FORMAT(`lastLogin`, '%r') FROM `users` WHERE `user_id`='%i', id);

the MySQL command is valid and the Query returns the right time format (I tested it directly in MySQL).

Now I want to store the result in a char* array but for some reason he always crashes with a SQL Invalid Command Exception when I try to copy the result in to the array.

time->first();
char* lastLogin = new char[50];

//here are the variants of the commands I tried, every one crashed:
strcpy(lastLogin, time->getString("lastLogin").c_str());
strcpy(lastLogin, time->getString("DATE_FORMAT(`lastLogin`, '%r')").c_str());
strcpy(lastLogin, time->getString("DATE_FORMAT(lastLogin, '%r')").c_str());
strcpy(lastLogin, time->getString(0).c_str());

does anybody know what I am doing wrong? Or is this even possible with MySQL Connector C++?


回答1:


Try naming the expression in your SQL, giving it an alias:

"SELECT DATE_FORMAT(`lastLogin`, '%r') as last_login_str FROM `users` WHERE `user_id`='%i'"

Then use "last_login_str" to retrieve the value.



来源:https://stackoverflow.com/questions/9045030/c-store-a-modified-mysql-timestamp-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!