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
相关推荐
逝水无殇15 分钟前
C# 运算符重载详解
开发语言·后端·c#
苏三说技术35 分钟前
2026编程圈很火的10个Skills
后端
TPBoreas40 分钟前
配置信息防泄露方案:.env 环境隔离详解(dotenv-java)
java·开发语言
用户83562907805143 分钟前
使用 Python 自动化 Excel 公式和函数:完整指南
后端·python
敲代码的嘎仔1 小时前
实习日志day6--实习日志day6--title命名规范化&businessType纠正&补充缺失的@Log注解&报警与通信模块补充&产出阶段总结文档
java·开发语言·人工智能·git·python·实习·大二
江华森1 小时前
Python 实现高德地图找房(一):环境搭建与数据爬虫
开发语言·爬虫·python
杜子不疼.1 小时前
【Qt初识】信号槽(三):机制意义、断开连接与 Lambda 表达式
开发语言·数据库·qt
编程(变成)小辣鸡2 小时前
Spring事务失效场景
java·后端·spring
PinkSun2 小时前
MySQL 建表报 1030,能查不能建,排查 1 小时发现是我自己改了一行权限
后端
无相求码2 小时前
为什么 printf 可以接受任意数量参数?变长参数的底层真相
后端