0

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?

cafce25
30.1k5 gold badges50 silver badges70 bronze badges
asked Jun 10, 2024 at 8:47
1
  • Can you try: result.push(row.get::<_, Option<String>>(0).unwrap().unwrap_or(String::new()))? (same for all 5 columns) Commented Jun 10, 2024 at 9:06

1 Answer 1

0

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();

Playground

answered Jun 10, 2024 at 9:15
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.