3

我有一个带有 NaiveDate 字段的结构,我想将此字段插入到表中。这是我的全部代码

use chrono::naive::NaiveDate; 
use rusqlite::{params, Connection, Result};

#[derive(Debug)]
struct Person {
    id: i32,
    name: String,
    date: NaiveDate,
}

fn main()->Result<()>{
    let date_str = "2020-04-12";
    let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();

    let me = Person {
        id: 0,
        name: "Steven".to_string(),
        date: naive_date,
    };
    println!("{:?}",me);
    
    let conn = Connection::open_in_memory()?;
    
        
    conn.execute(
        "CREATE TABLE person (
                  id              INTEGER PRIMARY KEY,
                  name            TEXT NOT NULL,
                  date            TEXT
                  )",
        [],
    )?;
    
    conn.execute(
    "INSERT INTO person (name, date) VALUES (?1, ?2)",
        params![me.name, me.date],
    )?;
    
    let mut stmt = conn.prepare("SELECT id, name, date FROM person")?;
    let person_iter = stmt.query_map([], |row| {
        Ok(Person {
            id: row.get(0)?,
            name: row.get(1)?,
            date: row.get(2)?,
        })
    })?;

    for person in person_iter {
        println!("Found person {:?}", person.unwrap());
    }
    
    Ok(())
}

但它给出了这两个错误

|   the trait `FromSql` is not implemented for `NaiveDate`
|   the trait `ToSql` is not implemented for `NaiveDate`

货物.toml

chrono = "0.4.19"
rusqlite = "0.25.0"
4

1 回答 1

3

您必须使用附加的 chrono 功能进行编译,才能为 chrono 类型实现FromSql和特征。ToSql

将 Cargo.toml 中的声明更改为

chrono = "0.4.19"
rusqlite = { version = "0.25.0", features = ["chrono"] }
于 2021-04-13T06:37:46.947 回答