Skip to content

Instantly share code, notes, and snippets.

@dcchut
Created August 4, 2019 16:19
Show Gist options
  • Save dcchut/9b3f59fab8d56afab7e2102ebe6f67a1 to your computer and use it in GitHub Desktop.
Save dcchut/9b3f59fab8d56afab7e2102ebe6f67a1 to your computer and use it in GitHub Desktop.
serde_postgres example
use postgres::{Connection, TlsMode};
use std::error::Error;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
struct Person {
name : String,
data : Vec<u8>,
}
fn main() -> Result<(), Box<Error>> {
let connection = Connection::connect("postgres://postgres@localhost:5432", TlsMode::None)?;
connection.execute("CREATE TABLE IF NOT EXISTS person (
id INTEGER NOT NULL,
name VARCHAR NOT NULL,
data BYTEA
);", &[])?;
connection.execute("INSERT INTO person (name, data) VALUES ($1, $2)", &[&"Jane", &"My data".as_bytes()])?;
connection.execute("INSERT INTO person (name, data) VALUES ($1, $2)", &[&"Alice", &"Alice's data".as_bytes()])?;
let rows = connection.query("SELECT name, data FROM person", &[])?;
let people = serde_postgres::from_rows::<Person>(&rows)?;
for person in people {
dbg!(person);
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment