The postgres crate provides a synchronous client for PostgreSQL. It is a lightweight wrapper around tokio-postgres that blocks on futures using a tokio runtime.
To connect, use Client::connect with a connection string and a TLS implementation. If you do not require TLS, use NoTls.
Common operations include:
batch_execute: Run multiple SQL statements at once.execute: Run a statement and return the number of rows affected.query: Run a statement and return a list of Row objects.row.get(index): Retrieve a value from a specific column in a row.
use postgres::{Client, NoTls};
fn main() -> Result<(), postgres::Error> {
let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
client.batch_execute("
CREATE TABLE person (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
data BYTEA
)
")?;
let name = "Ferris";
let data = None::<&[u8]>;
client.execute(
"INSERT INTO person (name, data) VALUES ($1, $2)",
&[&name, &data],
)?;
for row in client.query("SELECT id, name, data FROM person", &[])? {
let id: i32 = row.get(0);
let name: &str = row.get(1);
let data: Option<&[u8]> = row.get(2);
println!("found person: {} {} {:?}", id, name, data);
}
Ok(())
}