使用rust-postgres条板箱添加多行的最佳方法是什么?

时间:2018-10-22 06:52:52

标签: postgresql rust

我正在使用rust-postgres板条箱将数据插入PostgreSQL数据库。我从网站上抓取数据,并将其添加到数据库中。我不知道提前一次会添加多少行。在Rust中将多个行添加到Postgresql的最佳方法是什么?

我写了一个可能的解决方案,可以解决将所有元素从矢量写入数据库的一般问题。我使用迭代器而不是for循环,因为我喜欢它提供的功能样式。对于我来说,向每个元素发送INSERT命令到数据库似乎都不理想。有更好的方法吗?

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 个答案:

没有答案