how to use sql in rust

To use SQL in Rust, you can use the sqlx crate which provides a safe and convenient way to interact with a database using SQL.

To get started, add the sqlx and tokio crates to your Cargo.toml file:

[dependencies]
sqlx = "0.5"
sqlx-core = "0.5"
sqlx-rt = "0.5"
tokio = { version = "1", features = ["full"] }
109 chars
6 lines

Then, choose the appropriate database driver based on the database you're using. For example, if you're using PostgreSQL, add the sqlx-postgres crate:

[dependencies]
sqlx = "0.5"
sqlx-core = "0.5"
sqlx-rt = "0.5"
sqlx-postgres = "0.5"
tokio = { version = "1", features = ["full"] }
131 chars
7 lines

Next, set up a connection to your database using the connect function from the sqlx crate:

main.rs
use sqlx::{postgres::PgPoolOptions, Pool};

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool: Pool<Postgres> = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgresql://postgres:password@localhost/mydb")
        .await?;

    // Use the pool to execute SQL queries
    let rows = sqlx::query("SELECT name FROM users")
        .fetch_all(&pool)
        .await?;

    Ok(())
}
421 chars
17 lines

Lastly, use sqlx::query to send SQL statements to the database and fetch_all to get the result set. Method chaining can be used to pass in parameters to the query as well.

main.rs
let name = "Alice";
let rows = sqlx::query(
        r#"SELECT id, name, email FROM users WHERE name = $1"#,
        name,
    )
    .fetch_all(&pool)
    .await?;
163 chars
8 lines

Keep in mind, fetch_all will return all the rows at once, so use fetch_one if you only want to retrieve one row.

main.rs
let id = 123;
let row = sqlx::query(
        r#"SELECT name, email FROM users WHERE id = $1"#,
        id,
    )
    .fetch_one(&pool)
    .await?;
148 chars
8 lines

There are many other powerful features of sqlx, including support for transactions, prepared statements, and more. Check out the documentation for more information.

gistlibby LogSnag