expression

rusqlite: distinguish a missing row from a query error

OptionalExtension turns the no-row result into None while preserving other errors. This is separate from NULL inside an existing row. query_row uses the first returned row; enforce uniqueness with schema constraints when exactly one match is required. Run in the accompanying Cargo project. Expected stdout (not executed): found: false Common mistake: Replacing all database errors with None.

Formal Syntax & Structure

rust syntaxrust
conn.query_row(...).optional()?

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    use rusqlite::{Connection, OptionalExtension};    let db = Connection::open_in_memory()?;    db.execute("CREATE TABLE item (id INTEGER PRIMARY KEY, name TEXT)", [])?;    let name: Option<String> = db.query_row("SELECT name FROM item WHERE id = ?1", [7_i64], |r| r.get(0)).optional()?;    println!("found: {}", name.is_some());    Ok(())}
Rust Reference