rust连接postgresql数据库

同步操作

引入crate:

复制代码
postgres = "0.19.7"
rust 复制代码
use postgres::{Client, NoTls, error::Error};

fn main() -> Result<(), Error> {
    let mut client = Client::connect("host=localhost port=5432 dbname=xxxxxdb user=postgres password=123456", NoTls).unwrap();
    for row in client.query("select id,name,file_name,create_time::TEXT,valid from xxxxx", &[])?{
        let id: i32 = row.get("id");
        let name: &str = row.get("name");
        let file_name: &str = row.get("file_name");
        let create_time: &str = row.get(3);
        let valid: bool = row.get(4);
        println!("id:{}, name:{}, file_name:{},create_time:{:?} valid:{}", id, name, file_name,create_time, valid);
    }

     let rows = client.query("select count(*)::integer as a from xxxxx where id=$1", &[&1])?;
     let cnt: i32 = rows[0].get("a");
     println!("cnt={}", cnt);

    Ok(())
}

注意:用户名不要使用root。否则报错:

thread 'main' panicked at src\main.rs:5:115:

called `Result::unwrap()` on an `Err` value: Error { kind: Parse, cause: Some(Custom { kind: InvalidInput, error: Utf8Error { valid_up_to: 0, error_len: Some(1) } }) }

注意:select count(*) ::integer as a from xxxx的写法,做postgres内的类型转换,否则count(*)默认作为i8返回,rust获取数据时报错。

异步操作

引入Crate:

复制代码
tokio = {version = "1.35.1", features = ["full"]}
tokio-postgres = "0.7.10"
chrono = "0.4.34"
rust 复制代码
use tokio_postgres::{NoTls, Error};
use chrono::prelude::{DateTime, Utc};
use std::time::SystemTime;

#[tokio::main]
async fn main() -> Result<(), Error> {
    println!("测试tokio异步版本postgres操作");
    let (client, connection) = tokio_postgres::connect("host=localhost port=5432 dbname=xxxxxdb user=postgres password=123456", NoTls).await.unwrap();
    //启动线程监控数据库连接是否正常
    tokio::spawn(async move {
        if let Err(e) = connection.await{
            eprintln!("connection error:{}", e);
        }
    });
    let rows = client.query("select id,name,file_name,create_time,valid from xxxxx", &[]).await?;
    for row in rows{
        let id: i32 = row.get("id");
        let name: &str = row.get("name");
        let file_name: String = row.get("file_name");
        let create_time: SystemTime = row.get("create_time");
        let dt: DateTime<Utc> = create_time.clone().into();
        println!("id={}, name={}, file_name={}, create_time={}", id, name, file_name, dt.format("%Y-%M-%d %H:%m:%S"));
    }

    let rows = client.query("select max(id)::integer from xxxxx", &[]).await?;
    let max_id:i32 = rows[0].get(0);
    println!("max id={}", max_id);
    let new_id = max_id + 1;
    let new_name: String = format!("xxxxx-{}", new_id);
    let new_file_name: String = format!("xxxxx_file_name-{}", new_id);
    let modify_row_cnt = client.execute("insert into xxxxx(id,name,file_name,create_time,valid) values($1,$2,$3,$4,$5)", &[&new_id, &new_name, &new_file_name, &SystemTime::now(), &true]).await?;
    println!("affect row count:{}", modify_row_cnt);

    let affect_row_count = client.execute("update xxxxx set file_name='xxxxx_file_name-' || id::TEXT where file_name=''", &[]).await?;
    println!("affect row count:{}", affect_row_count);

    let affect_row_count = client.execute("delete from xxxxx where id=$1", &[&new_id]).await?;
    println!("delete row count:{}", affect_row_count);

    let trans = client.transaction().await?;
    trans.execute("update xxxxx set valid=$1,remark=name || id::TEXT where id=$2", &[&false, &1]).await?;
    trans.execute("update xxxxx set valid=$1,remark=name || id::TEXT where id=$2", &[&true, &2]).await?;
    trans.commit().await?;
    Ok(())
}

注意:postgresql中的timestamp类型可以直接转换为rust中的SystemTime;要转换为我们熟悉的年月日时分秒格式,还需要借助chrono crate。

代码中含增、删、改、查、事务范例。

相关推荐
知识分享小能手40 分钟前
Flask入门学习教程,从入门到精通,数据库操作 — 知识点详解与案例代码(4)
数据库·学习·flask
我是一颗柠檬1 小时前
【MySQL全面教学】MySQL基础SQL语句Day3(2026年)
数据库·后端·sql·mysql·oracle
XS0301061 小时前
MyBatis动态SQL
数据库·sql·mybatis
MandalaO_O1 小时前
MyBatis 与 MySQL 执行流程
数据库·mysql·mybatis
l1t2 小时前
DeepSeek总结的将 Rust Delta Kernel 集成到 ClickHouse
数据库·clickhouse·rust
qq_283720052 小时前
万字深度:Chroma 向量数据库全解析 — 核心原理、实战操作、性能优化与工程最佳实践
数据库·性能优化
黄筱筱筱筱筱筱筱2 小时前
二进制包安装MySql服务
数据库
初心未改HD3 小时前
LLM应用开发之向量数据库详解
数据库·人工智能
键盘上的猫头鹰3 小时前
【从零学MySQL(三)】数据增删改(DML)及 SELECT 查询详解
数据库·mysql·数据分析
KaMeidebaby3 小时前
卡梅德生物技术快报|蛋白的过表达质粒构建与生信分析实验全流程复盘
前端·数据库·其他·百度·新浪微博