I am using the below code to insert to a Postgres DB using tokio-postgres, is there any better option :
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, ¶ms[..]).await; //p is the pool manager
format!()
is smart enough to steal the value of the first argument if it's movable. At a minimum, I'd consider using concatenation instead of rebuilding the whole string each iteration. – PneumothoraxString
implementsstd::fmt::Write
, so you should be able to usewrite!
on the string to append a format to it. For example:write!(&mut qry, " (${})", i)?
– Pneumothoraxlet mut buf = String::new(); buf.write_fmt(format_args!("(${},${},${})",i,i+1,i+2));
– Anthracosilicosis