Expand description
sqlite 工具包
使用示例见单元测试
使用navicat可以创建sqlite数据库文件,以及查看表数据情况
方式一: 结构体使用派生宏,自动进行代码扩写
// 注意:这里需引入了两个FromSqliteRow,一个用于注解,一个用于扩写后的代码使用
use dev_tool::sqlite_util::{FromSqliteRow, SqliteClient};
use from_sqlite_row_macro::FromSqliteRow;
// 假设存在一个 users 表,定义对应的结构体
#[derive(Debug, FromSqliteRow)]
struct User {
id: i64, // 不要使用i32(其没有实现对应的trait)
name: String,
}
#[test]
fn it_works() {
let client = SqliteClient::new("test.db").expect("Failed to create SqliteUtil");
let user_results = client.query::<User>("SELECT id, name FROM users");
println!("User results: {:?}", user_results);
for item in user_results {
println!("id = {}, name = {}", item.id, item.name);
}
}方式二: 结构体自行进行实现FromSqliteRow
use dev_tool::sqlite_util::{FromSqliteRow, SqliteClient};
// 假设存在一个 users 表,定义对应的结构体
#[derive(Debug)]
struct User {
id: i64, // 不要使用i32(其没有实现对应的trait)
name: String,
}
// 为 User 结构体实现 FromSqliteRow trait
impl FromSqliteRow for User {
fn from_row(row: &sqlite::Row) -> Self {
User {
id: row.read::<i64, _>("id"),
name: row.read::<&str, _>("name").to_string(),
}
}
}
#[test]
fn it_works() {
let client = SqliteClient::new("test.db").expect("Failed to create SqliteUtil");
let user_results = client.query::<User>("SELECT id, name FROM users");
println!("User results: {:?}", user_results);
for item in user_results {
println!("id = {}, name = {}", item.id, item.name);
}
}Structs§
- Sqlite
Client - SQLite 客户端,用于连接SQLite数据库,可以进行crud操作
Traits§
- From
Sqlite Row - 将sqlite::Row转换为指定的类型