gpt4 book ai didi

c++ - 如何使用 MySQL Connector/C++ 获取 DATETIME 并存储到 time_t?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:19 59 4
gpt4 key购买 nike

我使用 MySQL Connector/C++ 作为库从 MySQL 数据库获取结果。我正在使用 C++11 标准。我想从数据库中获取一个 DATETIME 字段(名为 jointime)并将其存储为 time_t 变量如下:

#include <cstdlib>
#include <iostream>
#include <ctime>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
auto driver = sql::mysql::get_mysql_driver_instance();
auto con = driver->connect("tcp://127.0.0.1:3306", "user", "password");
con->setSchema("mydb");
auto stmt = con->createStatement();

auto res = stmt->executeQuery("SELECT * from users;");
while (res->next()) {
string username = res->getString("username");
time_t jt ; // res->get???
...
}
delete res;
delete stmt;
delete con;
}

如何获取jointime并将其分配给time_t jt

没有 getDateTime() 或相关方法。

最佳答案

MySQL 连接器/C++ 将 DATATIME 作为 string 返回。输出格式是%Y-%m-%d %H:%M:%S 所以你需要写下面的函数把这个字符串转换成time_t:

time_t String2time_t(const string& strDateTime){
tm t;
strptime(strDateTime.c_str(), "%F %T", &t);
return mktime(&t);
}

现在使用此行获取 DATETIME 并将其保存在 time_t 中:

time_t jt =  String2time_t((string)res->getString("jointime"));

注意 getString 的输出是 SQLstring 不是 std::string 所以你需要把它转换成 std::string 在传递给编写的函数之前。

关于c++ - 如何使用 MySQL Connector/C++ 获取 DATETIME 并存储到 time_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719983/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com