gpt4 book ai didi

rust - 如何使用 rusqlite 在 sqlite 数据库中插入和获取日期?

转载 作者:行者123 更新时间:2023-12-04 14:07:48 26 4
gpt4 key购买 nike

我有一个带有 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`

cargo .toml

chrono = "0.4.19"
rusqlite = "0.25.0"

最佳答案

您必须使用额外的计时功能进行编译,以便为计时类型实现 FromSqlToSql 特征。

将 Cargo.toml 中的声明更改为

chrono = "0.4.19"
rusqlite = { version = "0.25.0", features = ["chrono"] }

关于rust - 如何使用 rusqlite 在 sqlite 数据库中插入和获取日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67069764/

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