You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SQLx连接PostgreSQL时遇Tokio上下文错误,求排查

问题

参考SQLx官方快速入门文档连接PostgreSQL数据库,配置了包含postgres、runtime-tokio等特性的Cargo.toml,main.rs代码照搬文档并使用#[tokio::main]宏。但运行cargo run时出现panic错误:“this functionality requires a Tokio context”。能通过psql命令正常连接该数据库,请问遗漏了什么?

相关代码与信息

Cargo.toml

[dependencies]
sqlx = { version = "0.7", features = [ "postgres", "runtime-tokio", "tls-rustls" ] }
tokio = { version = "0.2.22", features = ["full"] }

main.rs

use sqlx::PgPool;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool = PgPool::connect("postgres://root:password@localhost:5555/test").await?;

    let row: (i64,) = sqlx::query_as("SELECT $1")
        .bind(150_i64)
        .fetch_one(&pool)
        .await?;

    assert_eq!(row.0, 150);

    Ok(())
}

错误信息

thread 'main' panicked at /Users/valentin/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sqlx-core-0.7.4/src/pool/inner.rs:500:5:
this functionality requires a Tokio context

psql连接命令

psql -h localhost -p 5555 -U root -d test

密码为password。

解决方案

问题核心是Tokio版本不兼容:

  • SQLx 0.7依赖的是Tokio 1.x版本,但当前配置的Tokio是0.2.22旧版本,两者运行时上下文不匹配,导致SQLx无法识别当前Tokio运行环境,触发panic。

修复步骤:

  1. 更新Cargo.toml中的Tokio版本到1.x,保持特性配置不变:
[dependencies]
sqlx = { version = "0.7", features = [ "postgres", "runtime-tokio", "tls-rustls" ] }
tokio = { version = "1.0", features = ["full"] }
  1. 执行cargo update更新依赖
  2. 重新运行cargo run即可正常连接数据库

内容的提问来源于stack exchange,提问作者Valentin Vignal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:57:13