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 rowsexecutefor 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
}