SQLx简介
SQLx是Rust语言中的一个异步SQL数据库连接库,它支持多种数据库,如PostgreSQL、MySQL和SQLite。SQLx提供了简单的API和异步执行查询的能力,使得Rust程序员可以轻松地与数据库交互1。
本章节以PostgreSQL为例。
目录结构
cargo.toml配置文件
[package]
name = "rust_model"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = {version = "1.37.0",features = ["full"]}
sqlx = { version = "0.7.4",features = ["postgres", "runtime-tokio-rustls","macros","chrono"]}
dotenv = {version = "0.15.0"}
chrono={version = "0.4.38", features = ["serde"]}
serde={version = "1.0.200", features = ["derive"]}
actix-web = "4.0.4"
actix-rt = "2.9.0"
[[example]]
name = "rustSQLx"
path = "examples/SQL/rustSQLx.rs"
doc-scrape-examples = true
[package.metadata.example.rustSQLx]
name = "Create SQL Database"
description = "demonstrates SQLx database create"
category = "SQL Rendering"
wasm = true
.env环境变量配置文件
DATABASE_URL=postgres://postgres:123456@127.0.0.1:5432/library
假设已有数据库library,创建表
DROP TABLE IF EXISTS course;
CREATE TABLE course (
id INT8 NOT NULL,
teacher_id INT4 NOT NULL,
name VARCHAR(255) NOT NULL,
time DATE DEFAULT NOW()
);
INSERT INTO course VALUES (1, 11, 'cml', '2022-03-25');
INSERT INTO course VALUES (2, 22, 'cc', '2022-03-25');
INSERT INTO course VALUES (3, 33, 'mm', '2022-03-25');
ALTER TABLE course ADD CONSTRAINT course_pkey PRIMARY KEY (id);
rustSQLx.rs执行文件
use chrono::NaiveDate;
use dotenv::dotenv;
use sqlx::postgres::PgPoolOptions;
use std::env;
use rand::Rng;
#[derive(Debug)]
pub struct Course {
pub id: i64,
pub teacher_id: i32,
pub name: String,
pub time: Option<NaiveDate>,
}
#[actix_rt::main]
async fn main() -> Result<(), sqlx::Error> {
dotenv().ok();
// 读取所有的环境变量
// for (key, value) in env::vars() {
// println!("环境变量内容:{}: {}", key, value);
// }
let connection_str = env::var("DATABASE_URL")
.expect("数据库连接字符串获取失败,请检查env文件是否已配置数据库连接字符串");
// println!("数据库连接字符串是:{}", connection_str);
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&connection_str)
.await?;
println!("db_pool is : {:?}", pool);
//查询所有
let list = sqlx::query!("select * from course")
.fetch_all(&pool)
.await?;
let mut vec = vec![];
for row in list {
vec.push(Course {
id: row.id,
teacher_id: row.teacher_id,
name: row.name,
time: row.time,
})
}
println!("数据库中的所有数据:{:#?}", vec);
//查询单个
let list2 = sqlx::query!(r#"select * from course where id = $1"#, 1)
.fetch_all(&pool)
.await?;
let mut vec2 = vec![];
for row in list2 {
vec2.push(Course {
id: row.id,
teacher_id: row.teacher_id,
name: row.name,
time: row.time,
})
}
println!("查询单个{:#?}", vec2);
let mut rng = rand::thread_rng();
println!("Random i32: {}", rng.gen::<i32>());
let upc = Course{
id: rng.gen::<i64>(),
teacher_id: rng.gen::<i32>(),
name: "YinThunder".to_string(),
time: None,
};
// 增加
let insert = sqlx::query!(
r#"INSERT INTO course VALUES ($1, $2, $3)"#,
upc.id as i32,
upc.teacher_id,
upc.name
)
.fetch_all(&pool)
.await?;
// 更新
let update = sqlx::query!(r#"UPDATE course SET name=$1 WHERE id = $2"#, "Amy",1)
.fetch_all(&pool)
.await?;
//删除
let delete = sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, 2)
.fetch_all(&pool)
.await?;
Ok(())
}
命令行执行
cargo run --example rustSQLx