write to postgre in rust

To write to a PostgreSQL database in Rust, we can use the sqlx crate, which provides a type-safe, async-friendly, and composable way of working with databases. Here's an example:

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

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    // Create a connection pool
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://user:password@host/database")
        .await?;

    // Define the SQL statement and the parameters
    let name = "Alice";
    let age = 25;
    let statement = "INSERT INTO people (name, age) VALUES ($1, $2)";
    
    // Execute the SQL statement
    let result = sqlx::query(statement)
        .bind(name)
        .bind(age)
        .execute(&pool)
        .await?;
    
    // Print the number of rows affected
    let rows_affected = result.rows_affected();
    println!("Inserted {} row(s)", rows_affected);

    Ok(())
}
764 chars
29 lines

In this example, we first create a connection pool to the PostgreSQL database using the PgPoolOptions struct and the connect() method. We then define the SQL statement and the parameters using the bind() method. Finally, we execute the SQL statement using the execute() method and print the number of rows affected.

Note that all the database operations are performed in an asynchronous context, thanks to the tokio runtime used by sqlx. Also, error handling is done using Result and the ? operator, which makes the code more concise and easier to read.

gistlibby LogSnag