Rust语言从入门到精通系列 - SeaORM框架实践(基础篇)

1 分钟阅读

SeaORM是一个基于Rust语言的ORM(对象关系映射)框架,它提供了一种简单的方式来操作SQL数据库。SeaORM的设计理念是将SQL查询和Rust代码结合在一起,从而提供更好的类型安全和代码可读性。

在本教程中,我们将介绍SeaORM的基本用法和进阶用法。我们将使用SQLite数据库来演示这些用法。

基础用法

在使用SeaORM之前,我们需要将其添加到我们的Rust项目中。cargo.toml添加依赖:

1
sea-orm = "0.11.3"

连接到数据库

在使用SeaORM之前,我们需要连接到一个数据库。我们可以使用DatabaseConnection结构体来完成这个任务。

1
2
3
4
5
6
7
8
9
use sea_orm::{DatabaseConnection, DatabaseConnectionInfo};

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let db_info = DatabaseConnectionInfo::from_env()?;
    let db_conn = DatabaseConnection::connect(&db_info).await?;
    // ...
    Ok(())
}

在上面的代码中,我们使用DatabaseConnectionInfo::from_env()方法从环境变量中获取数据库连接信息,并使用DatabaseConnection::connect()方法连接到数据库。

定义表

在SeaORM中,我们可以使用sea_query::Table结构体来定义表。我们可以定义表的名称、列名和列类型。

1
2
3
4
5
6
7
8
use sea_query::{ColumnDef, ColumnType, Table};

let users = Table::new("users")
    .add_column("id", ColumnType::Int(Some(11)).Unsigned(true).NotNull(true).AutoIncrement(true))
    .add_column("name", ColumnType::String(Some(256)).NotNull(true))
    .add_column("email", ColumnType::String(Some(256)).NotNull(true).Unique(true))
    .add_column("age", ColumnType::Int(Some(3)).Unsigned(true).NotNull(true))
    .set_primary_key(vec!["id"]);

在上面的代码中,我们定义了一个名为users的表,它有四个列:idnameemailageid列是自增的主键,nameemail列是字符串类型,age列是整数类型。

插入数据

在SeaORM中,我们可以使用InsertStatement结构体来插入数据。我们可以使用values()方法来设置要插入的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
use sea_orm::{entity::*, query::*, DatabaseConnection};

let user = User {
    name: "John Doe".to_owned(),
    email: "john.doe@example.com".to_owned(),
    age: 30,
};

let insert = Insert::single_into(User::table())
    .values(user.clone())
    .build();

let result = User::insert(insert).exec(&db_conn).await?;

在上面的代码中,我们使用Insert::single_into()方法和values()方法来设置要插入的值。我们使用User::table()方法来获取User实体的表格。最后,我们使用User::insert()方法和exec()方法来执行插入操作。

查询数据

在SeaORM中,我们可以使用SelectStatement结构体来查询数据。我们可以使用from()方法来设置要查询的表格,使用column()方法来设置要查询的列,使用where_expr()方法来设置查询条件。

1
2
3
4
5
6
7
8
use sea_orm::{entity::*, query::*, DatabaseConnection};

let query = Select::from_table(User::table())
    .column(User::all_columns)
    .where_expr(User::email.eq("john.doe@example.com"))
    .build();

let result = User::find_by_sql(query).one(&db_conn).await?;

在上面的代码中,我们使用Select::from_table()方法和column()方法来设置要查询的表格和列。我们使用where_expr()方法来设置查询条件。最后,我们使用User::find_by_sql()方法和one()方法来查询数据。

更新数据

在SeaORM中,我们可以使用UpdateStatement结构体来更新数据。我们可以使用set()方法来设置要更新的值,使用where_expr()方法来设置更新条件。

1
2
3
4
5
6
7
8
use sea_orm::{entity::*, query::*, DatabaseConnection};

let update = Update::table(User::table())
    .set(User::name, "Jane Doe")
    .where_expr(User::email.eq("john.doe@example.com"))
    .build();

let result = User::update(update).exec(&db_conn).await?;

在上面的代码中,我们使用Update::table()方法和set()方法来设置要更新的值。我们使用where_expr()方法来设置更新条件。最后,我们使用User::update()方法和exec()方法来执行更新操作。

删除数据

在SeaORM中,我们可以使用DeleteStatement结构体来删除数据。我们可以使用where_expr()方法来设置删除条件。

1
2
3
4
5
6
7
use sea_orm::{entity::*, query::*, DatabaseConnection};

let delete = Delete::from_table(User::table())
    .where_expr(User::email.eq("john.doe@example.com"))
    .build();

let result = User::delete(delete).exec(&db_conn).await?;

在上面的代码中,我们使用Delete::from_table()方法和where_expr()方法来设置删除条件。最后,我们使用User::delete()方法和exec()方法来执行删除操作。

进阶用法

关联表查询

在SeaORM中,我们可以使用JoinType枚举来设置关联类型。我们可以使用JoinOn结构体来设置关联条件。

1
2
3
4
5
6
7
8
use sea_orm::{entity::*, query::*, DatabaseConnection};

let query = Select::from_table(User::table())
    .inner_join(Post::table(), JoinOn::new(User::id, Post::user_id))
    .column((User::name, Post::title))
    .build();

let result = User::find_by_sql(query).all(&db_conn).await?;

在上面的代码中,我们使用Select::from_table()方法和inner_join()方法来设置关联表格。我们使用JoinOn::new()方法来设置关联条件。最后,我们使用User::find_by_sql()方法和all()方法来查询数据。

事务处理

在SeaORM中,我们可以使用Transaction结构体来处理事务。我们可以使用begin()方法来开始事务,使用commit()方法来提交事务,使用rollback()方法来回滚事务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use sea_orm::{entity::*, query::*, DatabaseConnection, Transaction};

let tx = Transaction::new(&db_conn).await?;

let user = User {
    name: "John Doe".to_owned(),
    email: "john.doe@example.com".to_owned(),
    age: 30,
};

let insert = Insert::single_into(User::table())
    .values(user.clone())
    .build();

let result = User::insert(insert).exec(&tx).await?;

let update = Update::table(User::table())
    .set(User::name, "Jane Doe")
    .where_expr(User::email.eq("john.doe@example.com"))
    .build();

let result = User::update(update).exec(&tx).await?;

tx.commit().await?;

在上面的代码中,我们使用Transaction::new()方法来开始事务。我们使用User::insert()方法和exec()方法来插入数据,使用User::update()方法和exec()方法来更新数据。最后,我们使用tx.commit()方法来提交事务。

总结

在本教程中,我们介绍了SeaORM的基本用法和进阶用法。SeaORM提供了一种简单的方式来操作SQL数据库,它将SQL查询和Rust代码结合在一起,提供了更好的类型安全和代码可读性。通过本教程的学习,我们可以更好地理解SeaORM的使用方法,从而更好地使用它来开发Rust应用程序。

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 TinyZ Zzh (包含链接: https://tinyzzh.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。 如有任何疑问,请 与我联系 (tinyzzh815@gmail.com)

TinyZ Zzh

TinyZ Zzh

专注于高并发服务器、网络游戏相关(Java、PHP、Unity3D、Unreal Engine等)技术,热爱游戏事业, 正在努力实现自我价值当中。

评论

  点击开始评论...