Rust语言

关注公众号 jb51net

关闭
首页 > 软件编程 > Rust语言 > Rust Postgres

Rust Postgres实例代码

作者:凝霜月冷残-草木破白衣

Rust Postgres是一个纯Rust实现的PostgreSQL客户端库,本文主要介绍了Rust Postgres实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

特点

目录结构

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

到此这篇关于Rust Postgres实例的文章就介绍到这了,更多相关Rust Postgres实例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文