Database queries and transactions
Quick answer
Database parameter binding keeps values separate from SQL syntax. A transaction groups related changes so they commit or roll back together.
Use a disposable database
Use SQLx 0.8.6 with default features disabled and runtime-tokio and sqlite enabled, plus Tokio 1.44.2 with rt and macros. These candidates reuse earlier version choices but switch to SQLite for local exercises. A single-connection in-memory pool avoids separate databases per connection. query checks SQL at execution, not Rust compilation; query! has additional compile-time schema requirements. Bind values with .bind; never concatenate user input into SQL. Table names cannot generally be passed as value parameters, so choose dynamic identifiers from a fixed allowlist.
use sqlx::sqlite::SqlitePoolOptions;#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; let name: String = sqlx::query_scalar("SELECT ?").bind("O'Neil").fetch_one(&p).await?; println!("{name}"); Ok(())}Manual local Rust/Cargo candidate; not executed. Expected behavior:
O'NeilThe apostrophe is data rather than SQL syntax.
use sqlx::sqlite::SqlitePoolOptions;#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY)").execute(&p).await?; let mut tx = p.begin().await?; sqlx::query("INSERT INTO items VALUES (?)").bind(1_i64).execute(&mut *tx).await?; tx.rollback().await?; let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM items").fetch_one(&p).await?; println!("{n}"); Ok(())}Manual local Rust/Cargo candidate; not executed. Expected behavior:
0The explicit rollback prevents this inserted row from persisting.
Common mistake
Do not mix pool queries with transaction queries when both must be atomic.
Try it yourself
Change rollback to commit and verify the row count becomes one.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database queries and transactions — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A person's name contains an apostrophe. How should a query pass it?
Database queries and transactions — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use sqlx::sqlite::SqlitePoolOptions; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; let name: String = sqlx::query_scalar("SELECT ?").bind("O'Neil").fetch_one(&p).await?; println!("{name}"); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Database queries and transactions — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use sqlx::sqlite::SqlitePoolOptions; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY)").execute(&p).await?; let mut tx = p.begin().await?; sqlx::query("INSERT INTO items VALUES (?)").bind(1_i64).execute(&mut *tx).await?; tx.rollback().await?; let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM items").fetch_one(&p).await?; println!("{n}"); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.