expression

SQLx QueryBuilder: construct a bounded bulk insert

A bulk insert groups multiple value tuples into a statement. Use push_bind for every field. Chunk large input before constructing statements; skip empty chunks. The example creates SQL text only and performs no insert. In production, a transaction may be necessary if all chunks must succeed together. No database connection is required by this example. Expected stdout (not executed): four bound fields Common mistake: Passing an empty batch, embedding values into SQL or confusing one bulk statement with an all-chunk transaction.

Formal Syntax & Structure

rust syntaxrust
builder.push_values(rows, |mut row, value| { ... });

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    use sqlx::{Postgres, QueryBuilder};    let items = [(1_i32, "Pen"), (2, "Book")];    let mut q = QueryBuilder::<Postgres>::new("INSERT INTO items (id, name) ");    q.push_values(items, |mut row, (id, name)| {        row.push_bind(id).push_bind(name);    });    assert!(q.sql().contains("$4"));    assert!(!q.sql().contains("Pen"));    println!("four bound fields");    Ok(())}
Rust Reference