C++ 将修改后的 MySQL 时间戳存储为字符串 [英] C++ store a modified MySQL timestamp as string
问题描述
我目前正在尝试从 MySQL 数据库中获取 DATETIME
键值并将其保存为字符串.
I am currently trying to get a DATETIME
key value from a MySQL database and save it as a string.
但是我不希望时间采用通常的 MySQL 格式 YYYY-MM-DD HH:MM:SS
而是采用这样的 12 小时格式:HH:MM:SS 上午/下午
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
我已经想出了如何使用以下方法将 MySQL 数据库中的时间格式转换"为我想要的格式:
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);
MySQL 命令有效,Query 返回正确的时间格式(我直接在 MySQL 中测试过).
the MySQL command is valid and the Query returns the right time format (I tested it directly in MySQL).
现在我想将结果存储在 char* 数组中,但由于某种原因,当我尝试将结果复制到数组时,他总是因 SQL 无效命令异常而崩溃.
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());
有人知道我做错了什么吗?或者这甚至可以用 MySQL Connector C++ 实现吗?
does anybody know what I am doing wrong? Or is this even possible with MySQL Connector C++?
推荐答案
尝试为 SQL 中的表达式命名,并给它一个别名:
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'"
然后使用 "last_login_str"
来检索值.
Then use "last_login_str"
to retrieve the value.
这篇关于C++ 将修改后的 MySQL 时间戳存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!