How to Write Raw SQL Queries in Rust

Execute raw SQL in Rust using the sqlx crate's query method with parameter binding.

Use the sqlx crate to execute raw SQL queries by creating a connection and calling query with your SQL string.

use sqlx::{SqlitePool, Row};

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool = SqlitePool::connect("sqlite::memory:").await?;
    let rows = sqlx::query("SELECT * FROM users WHERE id = ?")
        .bind(1)
        .fetch_all(&pool)
        .await?;
    Ok(())
}