I am trying to get the contents of different columns in a row. The database fields are TEXT
fields which allows for NULL
values, however, my code as illustrated down below produces the following error:
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
)", (),
).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 FROM test_table WHERE id = ?1", [1], |row| {
Ok({
result.push(row.get(0).unwrap());
})
}).unwrap();
I have thought about using while
+ match
Ok() Err() methods to row.get()
but apparently rusqlite
does not have an API for getting the len()
or looping of the .get()
function. Any ideas this problem could be solved and implemented?
The correct type for optional data (data which may be null
) is Option<T>
and that works:
// 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();