Rust Postgres实例

Rust Postgres介绍

Rust Postgres是一个纯Rust实现的PostgreSQL客户端库,无需依赖任何外部二进制文件2。这意味着它可以轻松集成到你的Rust项目中,提供对PostgreSQL的支持。

特点

  • 高性能:Rust Postgres提供了高性能的数据库交互功能,这对于需要处理大量数据的应用来说是非常重要的。
  • 安全性:由于Rust本身的设计就注重安全性,因此Rust Postgres也继承了这一特性,能够在编译期间检测并预防大部分潜在的安全问题。
  • 易用性:Rust Postgres的API设计简洁明了,易于理解和使用,这使得开发者能够快速上手并开始使用。

目录结构

cargo.toml配置文件

复制代码
[package]
name = "MyPostgres"
version = "0.1.0"
edition = "2021"

[dependencies]
postgres = "0.19.7"

[[example]]
name = "createPostgresDatabase"
path = "examples/SQL/createPostgresDatabase.rs"
doc-scrape-examples = true

[package.metadata.example.createPostgresDatabase]
name = "Create Postgres Database"
description = "demonstrates postgreSQL database create"
category = "SQL Rendering"
wasm = true

假设已有数据库library,初始数据库,可在官方下载软件,按照过程设置密码,本实例中是123456。

postgreSQL不允许管理员登录命令行,可以在路径.\PostgreSQL\16\pgAdmin 4\runtime找到pgAdmin4.exe打开可视化界面。

PostgreSQL: Windows installers

执行文件createPostgresDatabase.rs

增删改查

复制代码
use postgres::{Client, NoTls, Error};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
struct Author {
    _id: i32,
    name: String,
    country: String
}

struct Nation {
    nationality: String,
    count: i64,
}
fn establish_client() -> Client {

    Client::connect
        ("postgresql://postgres:123456@localhost/library", NoTls).expect("REASON")

}
fn main() -> Result<(), Error> {
    // let mut client =
    //     Client::connect("postgresql://postgres:123456@localhost/library", NoTls)?;

    let  client =Rc::new(RefCell::new(establish_client()));

    client.clone().borrow_mut().batch_execute("
        CREATE TABLE IF NOT EXISTS author (
            id              SERIAL PRIMARY KEY,
            name            VARCHAR NOT NULL,
            country         VARCHAR NOT NULL
            )
    ")?;

    client.clone().borrow_mut().batch_execute("
        CREATE TABLE IF NOT EXISTS book  (
            id              SERIAL PRIMARY KEY,
            title           VARCHAR NOT NULL,
            author_id       INTEGER NOT NULL REFERENCES author
            )
    ")?;


    let mut authors = HashMap::new();
    authors.insert(String::from("Chinua Achebe"), "Nigeria");
    authors.insert(String::from("Rabindranath Tagore"), "India");
    authors.insert(String::from("Anita Nair"), "India");

    for (key, value) in &authors {
        let author = Author {
            _id: 0,
            name: key.to_string(),
            country: value.to_string()
        };

        client.clone().borrow_mut().execute(
            "INSERT INTO author (name, country) VALUES ($1, $2)",
            &[&author.name, &author.country],
        )?;
    }

    for row in  client.clone().borrow_mut().query("SELECT id, name, country FROM author", &[])? {
        let author = Author {
            _id: row.get(0),
            name: row.get(1),
            country: row.get(2),
        };
        println!("Author {} is from {}", author.name, author.country);
    }

    client.clone().borrow_mut().execute("DROP TABLE book",&[]);
    // let result =
    //      client.clone().borrow_mut().execute
    //     ("DELETE FROM author WHERE id >= $1 AND id <= $2", &[&1i32, &100i32])?;
    //
    // println!("{:?}",result);
    let a2 = Author {
        _id: 0,
        name: "YinThunder".to_string(),
        country: "1".to_string()
    };
    let result =
        client.clone().borrow_mut().execute
        ("UPDATE  author SET name = $1 WHERE id >= $2 AND id <= $3", &[&a2.name,&1i32, &100i32])?;

    println!("{:?}",result);


    selectDataTable(client.clone());
    droptDataTable(client.clone());

    Ok(())

}
fn selectDataTable(client: Rc<RefCell<Client>>) ->Result<(), Error>{
    for row in client.borrow_mut().query("SELECT id, name, country FROM author", &[])? {
        let author = Author {
            _id: row.get(0),
            name: row.get(1),
            country: row.get(2),
        };
        println!("Author {} is from {}", author.name, author.country);
    }
    Ok(())
}
fn droptDataTable(client: Rc<RefCell<Client>>) ->Result<(), Error>{
    client.borrow_mut().execute("DROP TABLE author",&[]);
    Ok(())
}

命令行执行指令

复制代码
cargo run --example createPostgresDatabase
相关推荐
码事漫谈21 分钟前
OPC到底是什么:一年冒出1600万家,九成活不过2026年
后端
陆枫Larry27 分钟前
从一个 Java Demo 聊聊 H2 数据库的前世今生
后端
特立独行的猫A34 分钟前
仓颉版 Tauri 单文件 exe:gcc -r 一招破解 GCC-LTO 静态库链接
后端
金銀銅鐵37 分钟前
带您看懂字节码指令(番外二):递归里有什么——三层 fact 帧怎么叠起来
java·jvm·后端
皮皮林5511 小时前
私活神器,腾讯低代码平台开源了,拖拽就能开发~
后端
两点王爷3 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
用户112936112194 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
微笑星河q4 小时前
C++高阶之【多态】
开发语言·c++
想入Ai的菜鸡4 小时前
700 轮 A/B 实测:27B 的 FP8 与 AWQ-INT4 差多少?单卡 48G 上的量化选型(vLLM 0.34 + xhigh 思考)
后端·架构