在 Rust 中使用 Tokio-postgres 向 Postgres 插入多个值

multiple value inserts to Postgres using Tokio-postgres in Rust

我正在使用以下代码通过 tokio-postgres 插入到 Postgres 数据库中,有没有更好的选择:

let members = &[obj] //obj is a struct
let mut params = Vec::<&(dyn ToSql + Sync)>::new();
let mut i = 1;
let mut qry:String = "insert into tablename(id,userid,usertype) values".to_string();
for column in members{
    if(i ==1){
        qry = format!("{} (${},${},${})",qry,i,i+1,i+2);
    }else{
        qry = format!("{}, (${},${},${})",qry,i,i+1,i+2);

    }
    params.push(&column.id);
    params.push(&column.userid);
    params.push(&column.usertype);
    i = i+3;
               
}
println!("qry : {}",qry);
let result = p.execute(&qry, &params[..]).await; //p is the pool manager

否:

您可以通过使用迭代器略微改进它:

use itertools::Itertools; // For tuples() and format_with()

let params: Vec<_> = members
    .iter()
    .flat_map(|row| [&row.id as &(dyn ToSql + Sync), &row.userid, &row.usertype])
    .collect();
let query = format!(
    "insert into tablename(id, userid, usertype) values {}",
    (0..params.len())
        .tuples()
        .format_with(", ", |(i, j, k), f| {
            f(&format_args!("(${i}, ${j}, ${k})"))
        }),
);

不过我真的不认为那更好。