简体   繁体   English

在 Rust 中使用 tokio-postgres 调用执行函数之前如何准备查询参数?

[英]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] .虽然,我收到以下错误:expected reference &[&dyn ToSql + Sync]

I've tried setting the params to type "&[&dyn ToSql + Sync]"我尝试将参数设置为键入“&[&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.我也试过在数组上使用宏 to_sql_checked.() ......但这也不起作用。

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 .请注意分配给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‽如果不是,那么由于某种原因,您必须将params类型归因于您确实将类型归因于statement

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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