如何保持全球 Postgres 连接?

emi*_*dar 1 postgresql static global-variables rust

我想将 Postgres 连接存储在全局范围内,以便从模块中的任何函数进行访问。这是一个例子:

use postgres::{Client, NoTls};

static mut client: Option<Client> = None;

pub fn get_player(id: i32) {
    // Use global client connection object:
    for row in client.unwrap().query("SELECT * FROM public.\"User\" WHERE \"accountID\"=$1;",&[&id]).unwrap(){
        let id: i32 = row.get(0);
        let name: &str = row.get(1);

        println!("found player: {} {}", id, name);
    }
}

pub fn init() {
    let mut connection = Client::connect("host=localhost user=postgres", NoTls);
    match connection {
        Ok(cli) => {
            println!("Database connected.");
            client = Some(cli);
        }
        Err(_) => println!("Database ERROR while connecting."),
    }
}
Run Code Online (Sandbox Code Playgroud)

它没有按预期编译和工作,我不知道如何在 Rust 中实现它。

sch*_*ach 5

lazy_static这是一个提供r2d2_postgres数据库连接池的示例:

use r2d2_postgres::postgres::{NoTls, Client};
use r2d2_postgres::PostgresConnectionManager;

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref POOL: r2d2::Pool<PostgresConnectionManager<NoTls>> = {
        let manager = PostgresConnectionManager::new(
            // TODO: PLEASE MAKE SURE NOT TO USE HARD CODED CREDENTIALS!!!
            "host=localhost user=postgres password=password".parse().unwrap(),
            NoTls,
        );
        r2d2::Pool::new(manager).unwrap()
    };
}



pub fn get_player(id: i32) {
    // Use global client connection object:
    let mut client = POOL.get().unwrap();
    for row in client.query("SELECT * FROM public.\"User\" WHERE \"accountID\"=$1;",&[&id]).unwrap(){
        let id: i32 = row.get(0);
        let name: &str = row.get(1);

        println!("found player: {} {}", id, name);
    }
}
Run Code Online (Sandbox Code Playgroud)