SQLX documentation表示以下内容:

execute查询终结器返回受影响的行数(如果有),并删除所有收到的结果. 此外,还有fetchfetch_onefetch_optionalfetch_all个接收结果.

sqlx::query返回的Query类型将从数据库返回Row<'conn>.可以访问列值 按序号或按名字加row.get().由于Row在连接上保留了不变的borrow ,因此只有一个 Row个可能同时存在.

有没有办法既拿到rows_affected行又拿到排自己的?

我try 在有意回滚的事务中运行相同的查询两次,但当我收到SQL语句时,我已经处于事务的中间,并且我不能并行运行两个事务.

有没有办法不用运行两次就能完成呢?

我使用Rust、最新的SQLX和Postgres作为数据库.

推荐答案

您还需要futures个 crate :

[dependencies]
futures = { version = "0.3.28", default-features = false }
sqlx = { version = "0.7.2", features = ["runtime-tokio", "postgres"] }

然后你可以像这样搞恶作剧:

use futures::stream::StreamExt;
use sqlx::{postgres::PgPoolOptions, Either, PgPool, Row};

#[tokio::main]
async fn main() {
    # ...

    do_query(
        &pool,
        "INSERT INTO todos (description) VALUES ('One'), ('Two') RETURNING id",
    )
    .await;
    do_query(&pool, "DELETE FROM todos").await;
}

async fn do_query(pool: &PgPool, query: &str) {
    let prefix = query.split_whitespace().next().unwrap();

    let mut results = sqlx::query(query).fetch_many(pool);

    while let Some(result) = results.next().await {
        let either = result.unwrap();
        match either {
            Either::Left(res) => {
                let num = res.rows_affected();
                println!("[{prefix}] affected {num} rows");
            }
            Either::Right(row) => {
                let num = row.len();
                println!("[{prefix}] fetched {num} rows");
            }
        }
    }
}

它会回来的

[INSERT] fetched 1 rows
[INSERT] fetched 1 rows
[INSERT] affected 2 rows
[DELETE] affected 2 rows

Postgresql相关问答推荐

转换失败:(—122.763091,49.04676)转换为地理(位置)""

仅使用 ssl 连接到 Postgresql 数据库

在 Postgresql 中实现自定义运算符时出错

如何使 Postgres 优化引擎具有确定性

是否可以短时间运行 VACUUM FULL 并获得一些好处?

Supabase 数据库大小问题

如何为 JavaEE 应用程序中的 PostgreSQL 热备设置配置连接故障转移?

如何使用 ActiveRecord json 字段类型

PostgreSQL 在 mySQL 中的 date_trunc

Postgresql - 在 Big Data 库中使用数组的性能

是否可以在 PostgreSQL 中部分刷新materialized视图?

在不存在的行上有select for update块

当成功有时会导致退出代码为 1 时,如何可靠地确定 pg_restore 是否成功?

PostgreSQL:将结果数据从 SQL 查询导出到 Excel/CSV

python pip install psycopg2 安装错误

为什么 rake db:migrate 有时会在 structure.sql 中添加尾随空格?

Postgresql 中的 NOT EXISTS 子句

如何将表的一列复制到PostgreSQL中比较相同ID的另一表的列

ruby on rails jsonb 列默认值

用于将布尔列排序为 true、null、false 的 SQL