You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GridDB Rust客户端插入TIMESTAMP行时遇类型不匹配错误,如何解决?

GridDB Rust客户端插入TIMESTAMP列报错问题解决

问题原因

你直接传递了人类可读的时间字符串给TIMESTAMP列,但GridDB的TIMESTAMP类型本质是64位整数(自Unix纪元以来的毫秒数),并非字符串格式的时间,因此类型不匹配导致插入操作被拒绝。

正确实现方式

GridDB Rust客户端要求TIMESTAMP列的值为毫秒级Unix时间戳(i64类型),你需要先将时间字符串解析为时间对象,再转换为毫秒数,然后通过类型安全的方式插入。推荐使用Row构造器来明确指定各列类型,避免类型错误:

1. 添加依赖

首先在Cargo.toml中添加chrono库用于时间解析:

[dependencies]
griddb = "0.1.4" # 替换为你实际使用的版本
chrono = { version = "0.4", features = ["parse"] }

2. 修改代码

use griddb::{StoreFactory, Row};
use chrono::{DateTime, Utc};
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let props = vec![
        ("notification_member", "192.168.0.10:10001"),
        ("cluster_name", "myCluster"),
        ("database", "public"),
        ("user", "admin"),
        ("password", "admin"),
    ];

    let factory = StoreFactory::new();
    let store = factory.get_store(props)?;

    // 获取目标容器
    let mut container = store.get_container("events")?;

    // 将字符串时间解析为UTC时间对象
    let event_time = DateTime::parse_from_str("2026-05-06 10:30:00", "%Y-%m-%d %H:%M:%S")?
        .with_timezone(&Utc);
    // 转换为毫秒级Unix时间戳
    let timestamp_ms = event_time.timestamp_millis();

    // 使用Row构造器创建符合列类型的行
    let mut row = Row::new(&container)?;
    row.set_string(0, "1")?; // 对应id列(STRING类型)
    row.set_timestamp(1, timestamp_ms)?; // 对应event_time列(TIMESTAMP类型)
    row.set_string(2, "login")?; // 对应event_name列(STRING类型)

    // 插入行数据
    container.put_row(&row)?;

    println!("Row inserted");

    Ok(())
}

备选方式:使用字符串向量插入

如果坚持使用put方法传入字符串向量,需要将毫秒数转换为字符串传入(不推荐,缺乏类型校验):

// ... 省略其他代码
let timestamp_ms = event_time.timestamp_millis();
container.put(vec!["1", &timestamp_ms.to_string(), "login"])?;
// ...

内容的提问来源于stack exchange,提问作者Udit Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 21:53:14