我想将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."),
}
}
它不是编译&按预期工作,我不知道如何在Rust中制作。
这里有一个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);
}
}