0Pricing
Learn Rust Coding · Lesson

CRUD Operations

Query and execute.

CRUD with sqlx

CRUD means Create, Read, Update, Delete. sqlx splits these into two execution styles:

  • fetch_* for queries that return rows
  • execute for statements that change data

Create (INSERT)

Insert a row with bound parameters and run it via execute. Use RETURNING to get the generated id back.

use sqlx::{Pool, Postgres};

async fn create(pool: &Pool<Postgres>, name: &str) -> i32 {
    let rec = sqlx::query!(
        "INSERT INTO users (name) VALUES ($1) RETURNING id",
        name
    ).fetch_one(pool).await.unwrap();
    rec.id
}

All lessons in this course

  1. Connecting to a Database
  2. Compile-Time Checked Queries
  3. CRUD Operations
  4. Migrations
← Back to Learn Rust Coding