expression

rusqlite: explicitly roll back a transaction

Rollback discards the uncommitted changes in the transaction. An explicit rollback returns a Result, allowing the caller to handle cleanup errors. The transaction is consumed by this operation. Run in the accompanying Cargo project. Expected stdout (not executed): rows: 0 Common mistake: Using the transaction again after rollback consumes it.

Formal Syntax & Structure

rust syntaxrust
tx.rollback()?;

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    let mut db = rusqlite::Connection::open_in_memory()?;    db.execute("CREATE TABLE item (name TEXT)", [])?;    let tx = db.transaction()?;    tx.execute("INSERT INTO item VALUES ('Pen')", [])?;    tx.rollback()?;    let n: i64 = db.query_row("SELECT COUNT(*) FROM item", [], |r| r.get(0))?;    println!("rows: {n}");    Ok(())}
Rust Reference