所以我有这个使用rusqlite
的代码.而且效果很好.
pub struct Database {
conn: Connection,
}
impl Database {
pub fn get(self: &Self, id: Option<u64>, name: Option<&str>) -> Result<Option<Record>, Error> {
let mut stmt = match name {
Some(_) => { self.conn.prepare_cached(Self::STMT_GET_ID_NAME) },
None => { self.conn.prepare_cached(Self::STMT_GET_ID) }
}?;
let mut rows = match name {
Some(name) => { stmt.query(params![id, name]) },
None => { stmt.query(params![id]) }
}?;
let row = rows.next()?;
if let Some(row) = row {
let record = Record {
id: row.get(0)?,
parent: row.get(1)?,
name: row.get(2)?,
record_type: row.get(3)?,
timestamp: row.get(4)?,
created_at: row.get(5)?,
modified_at: row.get(6)?,
size: row.get(7)?,
hash: row.get(8)?,
inode: row.get(9)?
};
Ok(Some(record))
} else {
Ok(None)
}
}
}
我遇到的问题是match
陈述本质上是重复的.
我try 过这样的事情,但这行不通.
let (mut stmt, mut rows) = match name {
Some(name) => {
let mut stmt = self.conn.prepare_cached(Self::STMT_GET_ID_NAME)?;
let rows = stmt.query(params![id, name])?;
(stmt, rows)
}
None => {
let mut stmt = self.conn.prepare_cached(Self::STMT_GET_ID)?;
let rows = stmt.query(params![id])?;
(stmt, rows)
}
};
问题是编译器抱怨stmt
的生命周期
error[E0597]: `stmt` does not live long enough
error[E0505]: cannot move out of `stmt` because it is borrowed
我真的try 了很多东西,并try 疯狂地搜索.但我被困住了.
there甚至是一种不完全丑陋和惯用的方法吗?我觉得这是一个非常愚蠢的问题,而且我在这里错过了一些基本的东西..