What is the best way to add multiple rows using the rust-postgres crate?

Viewed 994

I am using the rust-postgres crate to insert data into a PostgreSQL database. I scrape data from a website and want to add it to the database. I do not know ahead of time how many rows I will add in one go. What is the best way to add multiple rows to a postgresql in rust?

I wrote a possible solution to the general problem of writing all elements from a vector to a database. I used iterators rather than a for loop because I like the functional style it provides. Sending an INSERT command to the database for every element seems not ideal to me. Is there a better way to do this?

extern crate postgres;

use postgres::{Connection, TlsMode};

struct Person {
    id: i32,
    name: String,
    data: Option<Vec<u8>>,
}

fn write2db(connection: &Connection, person: Person) -> () {
    connection
        .execute(
            "INSERT INTO person (id, name, data) VALUES ($1, $2, $3)",
            &[&person.id, &person.name, &person.data],
        )
        .unwrap();
}

fn main() {
    let conn = Connection::connect("postgres://postgres@localhost:5433", TlsMode::None).unwrap();
    conn.execute(
        "CREATE TABLE person (
                        id              SERIAL PRIMARY KEY,
                        name            VARCHAR NOT NULL,
                        data            BYTEA
                      )",
        &[],
    )
    .unwrap();
    let me = Person {
        id: 0,
        name: "Steven".to_string(),
        data: None,
    };
    let you = Person {
        id: 1,
        name: "Alice".to_string(),
        data: None,
    };
    let he = Person {
        id: 2,
        name: "Bob".to_string(),
        data: None,
    };
    let she = Person {
        id: 3,
        name: "Claire".to_string(),
        data: None,
    };

    let my_vec = vec![me, you, he, she];
    my_vec.into_iter().for_each(|a| write2db(&conn, a))
}
0 Answers
Related