调用 PostgreSQL 函数并获取结果,无需循环。

huangapple go评论58阅读模式
英文:

Call a PostgreSQL function and get result back with no loop

问题

我有一个与PostgreSQL数据库交互的简单Rust程序。

实际的代码如下:

for row in &db_client.query("select magic_value from priv.magic_value();", &[]).unwrap() {
    magic_value = row.get("magic_value");
    println!("Magic value is = {}", magic_value);
}

而且它有效。但我不喜欢它:我知道这个函数将返回一个且仅一个值。

从我找到的示例中,例如在这里:https://docs.rs/postgres/latest/postgres/index.html
以及在这里:https://tms-dev-blog.com/postgresql-database-with-rust-how-to/

你总是有一个记录集来循环。

哪种方式是在不循环的情况下调用函数的清洁方式?

英文:

I have a simple rust program that interacts with a PostgreSQL database.

The actual code is:

for row in &db_client.query("select magic_value from priv.magic_value();", &[]).unwrap()
{
	magic_value = row.get("magic_value");
	println!("Magic value is = {}", magic_value);
}

And.. it works. But I don't like it: I know this function will return one and only one value.

From the example I found, for example here: https://docs.rs/postgres/latest/postgres/index.html
and here: https://tms-dev-blog.com/postgresql-database-with-rust-how-to/

You always have a recordset to loop on.

Which is the clean way to call a function without looping?

答案1

得分: 1

query 返回一个 Result<Vec<Row>, _>。由于你已经解包了 Vec,所以你可以直接使用它,而不需要循环。通过将 Vec 转换为拥有所有权的迭代器,你甚至可以轻松地获取一个 Row,而不是 &Row

magic_value = db_client.query("select magic_value from priv.magic_value();", &[])
    .unwrap()    // -> Vec<Row>
    .into_iter() // -> impl Iterator<Item=Row>
    .next()      // -> Option<Row>
    .unwrap()    // -> Row
    .get("magic_value");
英文:

query returns a Result&lt;Vec&lt;Row&gt;, _&gt;. You are already unwrapping the Vec, so you can just use it directly instead of looping. By turning the Vec into an owning iterator yourself, you can even easily obtain a Row instead of a &amp;Row.

magic_value = db_client.query(&quot;select magic_value from priv.magic_value();&quot;, &amp;[])
    .unwrap()    // -&gt; Vec&lt;Row&gt;
    .into_iter() // -&gt; impl Iterator&lt;Item=Row&gt;
    .next()      // -&gt; Option&lt;Row&gt;
    .unwrap()    // -&gt; Row
    .get(&quot;magic_value&quot;);

</details>



huangapple
  • 本文由 发表于 2023年2月7日 03:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定