expression
Diesel: bind values and map raw SQL by name
Raw SQL remains useful for queries that are awkward in the typed DSL. Unlike the typed table query, this route decodes named columns via QueryableByName and does not statically validate arbitrary SQL text. Use fixed SQL and explicit parameter binding. SQLite uses ? placeholders. Uses a disposable in-memory SQLite database. Expected stdout (not executed): Book Common mistake: Interpolating user values into raw SQL or expecting the Rust compiler to validate the SQL string.
Formal Syntax & Structure
rust syntaxrust
diesel::sql_query(sql).bind::<diesel::sql_types::Integer, _>(id).get_result(&mut conn)?Working Example
Example Snippetrust
use diesel::prelude::*;use diesel::sqlite::SqliteConnection;
diesel::table! { items (id) { id -> Integer, label -> Text, note -> Nullable<Text>, }}
fn sample_db() -> Result<SqliteConnection, Box<dyn std::error::Error>> { let mut conn = SqliteConnection::establish(":memory:")?; diesel::sql_query("CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT NOT NULL, note TEXT)") .execute(&mut conn)?; diesel::insert_into(items::table) .values((items::id.eq(1), items::label.eq("Pen"))) .execute(&mut conn)?; diesel::insert_into(items::table) .values((items::id.eq(2), items::label.eq("Book"), items::note.eq(Some("blue")))) .execute(&mut conn)?; Ok(conn)}
fn main() -> Result<(), Box<dyn std::error::Error>> { #[derive(QueryableByName)] struct Label { #[diesel(sql_type = diesel::sql_types::Text)] label: String } let mut conn = sample_db()?; let row: Label = diesel::sql_query("SELECT label FROM items WHERE id = ?") .bind::<diesel::sql_types::Integer, _>(2_i32).get_result(&mut conn)?; println!("{}", row.label); Ok(())}