简体   繁体   中英

How do I prepare query parameters before calling the execute function with tokio-postgres in Rust?

I have the following code:

let query = "INSERT INTO users (uuid, pass) VALUES = $1, $2"; 
let statement = db_client.prepare(query).await?
let params = [&user.uuid, &user.pass];
let res = db_client.execute(&statement, params).await?;

Although, I am getting the following error: expected reference &[&dyn ToSql + Sync] .

I've tried setting the params to type "&[&dyn ToSql + Sync]"

let statement: &[&dyn ToSql + Sync] = db_client.prepare(query).await?

but, no avail.

I've also tried using the macro, to_sql_checked.() on the array... but this does not work either.

Regardless, the following code works:

let res = db_client.execute(&statement, &[&user.uuid, &user.pass]).await?;

What is really the difference here? I believe the code would be better if I was able to preassign the query values before sending them. What is the proper way to do this?

This should work:

let query = "INSERT INTO users (uuid, pass) VALUES = $1, $2"; 
let statement = db_client.prepare(query).await?
let params = &[&user.uuid, &user.pass];
let res = db_client.execute(&statement, params).await?;

Note the extra borrow in front of the array assigned to params .

If it doesn't then you have to ascribe the type of params for some reason you did ascribe a type to statement instead‽

let params: &[&dyn ToSql + Sync] = &[&user.uuid, &user.pass];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM