How to Use PostgreSQL with Rust

Complete Guide

Connect to PostgreSQL in Rust using the native postgres crate and execute queries with a Client instance.

Use the postgres crate to connect to PostgreSQL from Rust by adding it as a dependency and initializing a client with your connection string.

[dependencies]
postgres = "0.17.3"
use postgres::{Client, NoTls};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    let rows = client.query("SELECT name, age FROM users WHERE age > $1", &[&18])?;
    for row in rows {
        println!("Name: {}, Age: {}", row.get::<_, String>(0), row.get::<_, i32>(1));
    }
    Ok(())
}