如何使用MySQL C++ Connector 8.0读取ISO 8601格式的日期时间

3df52oht  于 2022-12-15  发布在  Mysql
关注(0)|答案(1)|浏览(157)

我想用MySQL C连接器8.0读取DATETIME,ISO 8601格式。我读过很多例子,但它们似乎都太复杂了,有些不起作用。这样的例子非常复杂,似乎有很多代码,而且非常不稳定。如果DATETIME包含微秒,有没有更好的方法来读取DATETIME
解释mysql连接器c
字段值的原始4字节为日期

lb3vh1jj

lb3vh1jj1#

是的。是的。
下面是代码。DATETIME被解释为数据类型RAW

std::vector<std::vector<std::string>> getDatabaseValues(const char tableName[]) {
    std::vector<std::string> values;
    std::vector<std::vector<std::string>> table;
    if (isConnectedToDatabase()) {
        // Select only the first row
        std::string query = "SELECT * FROM " + std::string(tableName);
        mysqlx::SqlResult result = connection->sql(query).execute();
        int columnCount = result.getColumnCount();
        if (result.hasData()) {
            mysqlx::Row row;
            while (row = result.fetchOne()) {
                for (int i = 0; i < columnCount; i++) {
                    switch (row[i].getType()) {
                    case mysqlx::common::Value::UINT64:
                        values.push_back(std::to_string(row[i].get<uint64_t>()));
                        break;
                    case mysqlx::common::Value::INT64:
                        values.push_back(std::to_string(row[i].get<int64_t>()));
                        break;
                    case mysqlx::common::Value::FLOAT:
                        values.push_back(std::to_string(row[i].get<float>()));
                        break;
                    case mysqlx::common::Value::STRING:
                        values.push_back(row[i].get<std::string>());
                        break;
                    case mysqlx::common::Value::RAW:
                        mysqlx::bytes data = row[i].getRawBytes();
                        const mysqlx::byte* first = data.begin();
                        int lengthOfData = data.length();
                        switch (lengthOfData) {
                        case 10: // DATETIME(6)
                            int year = (first[1] << 7) | (first[0] & 0x7f);
                            int month = first[2];
                            int date = first[3];
                            int hour = first[4];
                            int minute = first[5];
                            int second = first[6];
                            int microsecond = (first[9] << 14) | (first[8] << 7) | (first[7] & 0x7f);
                            char text[20];
                            sprintf(text, "%i-%i-%i %i:%i:%i.%i", year, month, date, hour, minute, second, microsecond);
                            values.push_back(text);
                            break;
                        }
                        
                        
                    }
                }
                table.push_back(values);
                values.clear();
            }
        }
    }
    return table;
}

理论是这样的

https://dev.mysql.com/doc/dev/mysql-server/latest/group__MY__TIME.html#datetime_and_date_low_level_rep

相关问题