学习Rust编程——r2d2连接池

学习Rust编程——r2d2连接池[dependencies]r2d2 = “0.8.10”r2d2_postgres = “0.18”/

大家好,欢迎来到IT知识分享网。

[dependencies] r2d2 = "0.8.10" r2d2_postgres = "0.18"
// r2d2_demo/src/main.rs use std::thread; use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager}; use std::time::Duration; const DROP_TABLE: &str = "DROP TABLE IF EXISTS books"; const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS books (id SERIAL PRIMARY KEY, title VARCHAR NOT NULL, author VARCHAR NOT NULL, year SERIAL)"; #[derive(Debug)] struct Book { id: i32, title: String, author: String, year: i32 } fn main() { let manager = PostgresConnectionManager::new("postgres://postgres:postgres@localhost:5432".parse().unwrap(), NoTls); let pool = r2d2::Pool::new(manager).unwrap(); let mut conn = pool.get().unwrap(); let _ = conn.execute(DROP_TABLE, &[]).unwrap(); let _ = conn.execute(CREATE_TABLE, &[]).unwrap(); thread::spawn(move || { let book = Book { id: 3, title: "A programmers introduction to mathematics".to_string(), author: "Dr. Jeremy Kun".to_string(), year: 2018 }; conn.execute("INSERT INTO books (id, title, author, year) VALUES ($1, $2, $3, $4)", &[&book.id, &book.title, &book.author, &book.year]).unwrap(); }); thread::sleep(Duration::from_millis(100)); for _ in 0..8 { let mut conn = pool.get().unwrap(); thread::spawn(move || { for row in &conn.query("SELECT id, title, author, year FROM books", &[]).unwrap() { let book = Book { id: row.get(0), title: row.get(1), author: row.get(2), year: row.get(3) }; println!("{:?}", book); } }); } } 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/47652.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信