在现代Rust开发中,高效、安全地与数据库交互是构建后端服务的关键环节。而 SQLx 正是目前最受欢迎的 Rust异步SQL库 之一。它支持编译时 SQL 查询校验、类型安全绑定、以及对 PostgreSQL、MySQL、SQLite 和 MSSQL 的原生异步支持。
tokio 或 async-std,无阻塞 I/O。首先,在终端中创建一个新的 Rust 项目:
cargo new rust_sqlx_democd rust_sqlx_demo 然后编辑 Cargo.toml 文件,添加 SQLx 依赖。以 PostgreSQL 为例(这也是最常用的场景之一):
[dependencies]tokio = { version = "1", features = ["full"] }sqlx = { version = "0.7", features = [ "runtime-tokio-rustls", "postgres", "uuid", "chrono", "json"] }uuid = { version = "1", features = ["v4"] }chrono = { version = "0.4", features = ["serde"] } 注意:runtime-tokio-rustls 表示使用 Tokio 作为异步运行时,并通过 Rustls 进行 TLS 加密(适用于云数据库)。如果你使用 MySQL,只需将 postgres 替换为 mysql。
接下来,我们编写代码连接到 PostgreSQL 数据库。确保你本地或远程有一个可访问的 PostgreSQL 实例。
use sqlx::PgPool;#[tokio::main]async fn main() -> Result<(), sqlx::Error> { // 从环境变量或硬编码获取数据库 URL let database_url = "postgres://user:password@localhost/mydb"; // 创建连接池 let pool = PgPool::connect(database_url).await?; println!("✅ 成功连接到数据库!"); Ok(())} 这段代码展示了如何使用 PgPool::connect 建立一个异步连接池。这是 Rust数据库操作 的基础。
现在我们来查询数据。假设数据库中有一张 users 表:
CREATE TABLE users ( id UUID PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, created_at TIMESTAMPTZ DEFAULT NOW()); 在 Rust 中定义对应的结构体,并使用 sqlx::FromRow 自动映射:
use sqlx::FromRow;use uuid::Uuid;use chrono::{DateTime, Utc};#[derive(Debug, FromRow)]pub struct User { pub id: Uuid, pub name: String, pub email: String, #[sqlx(default)] pub created_at: DateTime,} 然后执行查询:
#[tokio::main]async fn main() -> Result<(), Box> { let pool = PgPool::connect("postgres://user:password@localhost/mydb").await?; // 查询所有用户 let users: Vec = sqlx::query_as!(User, "SELECT * FROM users") .fetch_all(&pool) .await?; for user in users { println!("用户: {} ({})", user.name, user.email); } Ok(())} 注意这里使用了 query_as! 宏——这是 SQLx 的核心魔法之一!它会在编译时检查 SQL 语句是否合法,并验证返回的列是否能匹配 User 结构体。如果表结构变了但代码没改,编译就会失败,从而避免运行时 bug。
安全地插入数据,防止 SQL 注入:
use uuid::Uuid;let new_user_id = Uuid::new_v4();let name = "张三".to_string();let email = "zhangsan@example.com".to_string();sqlx::query!( r#"INSERT INTO users (id, name, email) VALUES ($1, $2, $3)"#, new_user_id, name, email).execute(&pool).await?; SQLx 会自动处理参数绑定,确保安全。对于 PostgreSQL 使用 $1, $2...,MySQL 则用 ? 占位符。
.env 文件配合 dotenv crate。PgPool,不要每次查询都新建连接。anyhow 或 thiserror 提升错误信息可读性。sqlx-cli 进行数据库迁移(cargo install sqlx-cli)。通过本教程,你应该已经掌握了如何使用 Rust SQLx教程 中的核心技能:连接数据库、查询、插入和类型安全映射。SQLx 让你在享受 SQL 灵活性的同时,获得 Rust 强大的编译时安全保障。无论你是构建微服务、API 后端还是数据管道,SQLx连接PostgreSQL 都是一个高效可靠的选择。
关键词回顾:Rust SQLx教程、Rust数据库操作、SQLx连接PostgreSQL、Rust异步SQL库
本文由主机测评网于2025-12-11发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126074.html