如何使用 rusqlite 在 sqlite 数据库中插入和获取日期?
How to insert and fetch date in a sqlite database using rusqlite?
我有一个带有 NaiveDate 字段的结构,我想将这个字段插入 table。这是我的全部代码
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"
您必须使用额外的计时功能进行编译才能为计时类型实现 FromSql
和 ToSql
特征。
将 Cargo.toml 中的声明更改为
chrono = "0.4.19"
rusqlite = { version = "0.25.0", features = ["chrono"] }
我有一个带有 NaiveDate 字段的结构,我想将这个字段插入 table。这是我的全部代码
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"
您必须使用额外的计时功能进行编译才能为计时类型实现 FromSql
和 ToSql
特征。
将 Cargo.toml 中的声明更改为
chrono = "0.4.19"
rusqlite = { version = "0.25.0", features = ["chrono"] }