expression

SQLx QueryBuilder: reset before reuse

After building a query, reset the builder before constructing another statement. Reset restores the initial SQL fragment and clears previous arguments. The first query borrows the builder, so release it before resetting. Reuse here is instructional, not a performance benchmark. No database connection is required by this example. Expected stdout (not executed): SELECT $1 SELECT $1 Common mistake: Appending another fragment to a builder that has already built a query without resetting it.

Formal Syntax & Structure

rust syntaxrust
let query = builder.build(); drop(query); builder.reset();

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    use sqlx::{Execute, Postgres, QueryBuilder};    let mut q = QueryBuilder::<Postgres>::new("SELECT ");    q.push_bind(10_i32);    let first = q.build();    println!("{}", first.sql());    drop(first);    q.reset();    q.push_bind(20_i32);    let second = q.build();    println!("{}", second.sql());    Ok(())}
Rust Reference