Last active
May 15, 2024 14:45
-
-
Save harryhanYuhao/03eabc3293e1d408fb538965e9fe6998 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cargo.toml | |
// [dependencies] | |
// tokio = { version = "1", features = ["full"] } | |
// sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] } | |
use sqlx::postgres::PgPoolOptions; | |
use sqlx::{Column, Executor, Row, TypeInfo, ValueRef}; | |
struct Data { | |
id: i32, | |
vendor_name: String, | |
} | |
#[tokio::main] | |
// or #[actix_web::main] | |
async fn main() -> Result<(), sqlx::Error> { | |
let pool = PgPoolOptions::new() | |
.max_connections(5) | |
.connect("postgres://postgres:password@localhost/suppliers") | |
.await?; | |
// execute a SQL INSERT INTO COMMAND | |
let mut rows = sqlx::query("INSERT INTO vendors (vendor_name) VALUES ($1) RETURNING vendor_id") | |
.bind("New Vendor") | |
.fetch_all(&pool) | |
.await?; | |
let mut rows = sqlx::query("SELECT * FROM vendors") | |
.fetch_all(&pool) | |
.await?; | |
let mut data_vec: Vec<Data> = Vec::new(); | |
for row in rows.iter_mut() { | |
data_vec.push(Data { | |
id: row.get::<i32, _>("vendor_id"), | |
vendor_name: row.get::<String, _>("vendor_name"), | |
}); | |
} | |
for data in data_vec.iter() { | |
println!("id: {}, vendor_name: {}", data.id, data.vendor_name); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment