我正在使用 Rust 的 rusqlite
用于从 sqlite 数据库插入和调用数据的 crate。
我正在使用 get()
其方法 Row
返回 Result<T>
。我有当前的代码片段:
while let Some(row) = rows.next()? {
let value = match row.get(0).expect("Could not get value from database cell.") {
// Do something here to specify types and return them or add them to a separate collection
};
}
如何指定类型?目前,我可以正确打开 get
的唯一方法函数的方法是将其分配给已经具有特定类型的变量,例如 let value: i64 = row.get(0).unwrap()
,但我不知道如何区分 get(0)
实际上是字符串、 bool 值或任何其他可接受的 SQL 类型。
我搜索了 match
的其他示例与 Result
,但它们的匹配枚举基于值,而不是类型。
最佳答案
How could I specify the type? Currently the only way I can properly unwrap the get function is by assigning it to a variable with a specific type already, like
let value: i64 = row.get(0).unwrap()
如果我正确理解你想要什么,你正在寻找 get_raw
和 get_raw_checked
返回 a ValueRef
enum这样您就可以在运行时检查检索到的值是什么类型:
while let Some(row) = rows.next()? {
let value = match row.get_raw(0) {
ValueRef::Null => ...
ValueRef::Integer(i) => ...
ValueRef::Real(f) => ...
ValueRef::Text(t) => ...
ValueRef::Blob(b) => ...
}
}
get
表示一个期望,如果违背期望,则返回一个 Err
,因为通常您知道存储在列中的值的类型应该 是的,如果有人在你下面替换了列或值的类型,那么一切都会被破坏。它还可以方便地处理various conversions因此您不必手动处理它们。
顺便说一句,如果您不想处理 get
可能出现的错误,您可以使用其兄弟 get_unwrap
.
关于sql - 如何对编译时不知道的类型使用 rusqlite 的 Row::get 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60396593/