expression

r2d2: borrow and return a pooled SQLite connection

A pool keeps a bounded set of connections and lends them to callers. Dropping a checkout releases it to the pool. Use a single-connection in-memory adapter here for a small demonstration; do not infer multi-connection storage behavior from it. r2d2 checkout and rusqlite queries are synchronous and can block. Run in the accompanying Cargo project. Expected stdout (not executed): first: 8 second: 9 Common mistake: Holding a checked-out connection while doing unrelated slow work.

Formal Syntax & Structure

rust syntaxrust
Pool::builder().max_size(1).build(manager)?; pool.get()?

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    use r2d2::Pool;    use r2d2_sqlite::SqliteConnectionManager;    let manager = SqliteConnectionManager::memory();    let pool = Pool::builder().max_size(1).build(manager)?;    {        let conn = pool.get()?;        let n: i64 = conn.query_row("SELECT 8", [], |r| r.get(0))?;        println!("first: {n}");    }    let conn = pool.get()?;    let n: i64 = conn.query_row("SELECT 9", [], |r| r.get(0))?;    println!("second: {n}");    Ok(())}
Rust Reference