Rust Postgres实例

发布于:2024-05-07 ⋅ 阅读:(20) ⋅ 点赞:(0)

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