sqlx执行案例

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
相关推荐
lucky_syq33 分钟前
Hive SQL和Spark SQL的区别?
hive·sql·spark
微服务 spring cloud4 小时前
配置PostgreSQL用于集成测试的步骤
数据库·postgresql·集成测试
溟洵8 小时前
Linux下学【MySQL】表中插入和查询的进阶操作(配实操图和SQL语句通俗易懂)
linux·运维·数据库·后端·sql·mysql
路在脚下@12 小时前
spring boot的配置文件属性注入到类的静态属性
java·spring boot·sql
Sunyanhui117 小时前
牛客网 SQL36查找后排序
数据库·sql·mysql
Mitch31119 小时前
【漏洞复现】CVE-2021-45788 SQL Injection
sql·web安全·docker·prometheus·metersphere
zxrhhm19 小时前
PostgreSQL的交互式终端使用一系列命令来获取有关文本搜索配置对象的信息
数据库·postgresql
一心只为学19 小时前
PostgreSql+Pgpool-II配置高可用集群(超详细)
数据库·postgresql·高可用·pgpool
网络安全King19 小时前
网络安全 - SQL Injection
sql·web安全·php
Stanford_110621 小时前
高级的SQL查询技巧有哪些?
sql·微信小程序·twitter·微信开放平台