Advertisement
NLinker

Async postgres client (compact api)

Nov 7th, 2019
1,670
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.29 KB | None | 0 0
  1. [package]
  2. name = "tokio-psql"
  3. version = "0.1.0"
  4. authors = ["Jinhua Luo <home_king@163.com>"]
  5. edition = "2018"
  6.  
  7. [dependencies]
  8. futures-preview = "=0.3.0-alpha.19"
  9. tokio = "0.2.0-alpha.6"
  10. tokio-postgres= { git = "https://github.com/sfackler/rust-postgres" }
  11.  
  12. --------------
  13.  
  14. use futures::FutureExt;
  15. use tokio_postgres::{Error, NoTls, Row};
  16.  
  17. #[tokio::main]
  18. async fn main() -> Result<(), Error> {
  19.     // Connect to the database.
  20.     let (client, connection) =
  21.         tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;
  22.  
  23.     // The connection object performs the actual communication with the database,
  24.     // so spawn it off to run on its own.
  25.     let connection = connection.map(|r| {
  26.         if let Err(e) = r {
  27.             eprintln!("connection error: {}", e);
  28.         }
  29.     });
  30.     tokio::spawn(connection);
  31.  
  32.     // Now we can prepare a simple statement that just returns its parameter.
  33.     let stmt = client.prepare("SELECT $1::TEXT").await?;
  34.  
  35.     // And then execute it, returning a Stream of Rows which we collect into a Vec.
  36.     let rows: Vec<Row> = client.query(&stmt, &[&"hello world"]).await?;
  37.  
  38.     // Now we can check that we got back the same string we sent over.
  39.     let value: &str = rows[0].get(0);
  40.     assert_eq!(value, "hello world");
  41.  
  42.     Ok(())
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement