我正在尝试获取连续不同列的内容。数据库字段是
TEXT
字段,允许使用 NULL
值,但是,如下所示的我的代码会产生以下错误:
Finished dev [unoptimized + debuginfo] target(s) in 1.25s
thread 'main' panicked at src\test_db.rs:7:36:
called `Result::unwrap()` on an `Err` value: InvalidColumnType(0, "name", Null)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
// Open connection
let conn = Connection::open(":memory:").unwrap();
// Create test_table
conn.execute(
"CREATE TABLE IF NOT EXISTS test_table (
id INTEGER PRIMARY KEY,
name TEXT,
last_name TEXT,
email TEXT,
phone TEXT,
address TEXT
)", (),
).unwrap();
// Insert demo row
conn.execute("INSERT INTO test_table (id) VALUES (?1)", [1]).unwrap();
// Prepare an empty vector to store column data even if is empty string
let mut result: Vec<String> = Vec::new();
// The actual query
conn.query_row("SELECT name, last_name, email, phone, address FROM test_table WHERE id = ?1", [1], |row| {
Ok({
result.push(row.get(0).unwrap());
result.push(row.get(1).unwrap());
result.push(row.get(2).unwrap());
result.push(row.get(3).unwrap());
result.push(row.get(4).unwrap());
})
}).unwrap();
我曾考虑过使用
while
+ match
Ok() Err() 方法来 row.get()
但显然 rusqlite
没有用于获取 len()
或循环 .get()
函数的 API。有什么想法可以解决和实施这个问题吗?
可选数据(数据可能是
null
)的正确类型是Option<T>
并且有效:
// Prepare an empty vector to store column data even if is empty string
let mut result: Vec<Option<String>> = Vec::new();
// The actual query
conn.query_row("SELECT name FROM test_table WHERE id = ?1", [1], |row| {
result.push(row.get(0)?);
Ok(())
})
.unwrap();